VS2010扩展中的文本视图语言

时间:2010-09-29 15:44:36

标签: c# visual-studio-2010 visual-studio-addins vsix

我是为Visual Studio构建插件的新手,但他们设法为VS2010构建了一个简单的工具,可以在当前活动的代码窗口中进行一些文本操作。我已经到了需要了解当前文本视图的语言(VB.Net,C#或其他)的地方。

我尝试使用以下代码获取文件名(因此我可以查看扩展名以确定语言):

IVsTextManager txtMgr = (IVsTextManager)GetService(typeof(SVsTextManager));
int mustHaveFocus = 1;//means true
txtMgr.GetActiveView(mustHaveFocus, null, out currentTextView);

userData = currentTextView as IVsUserData;
if (userData == null)// no text view 
{
    Console.WriteLine("No text view is currently open");
    return;
}

object pathAsObject;
Guid monikerGuid = typeof(IVsUserData).GUID;
userData.GetData(ref monikerGuid, out pathAsObject);
string docPath = (string)pathAsObject;

不幸的是,pathAsObject始终返回null。有没有其他方法来获取文件名/语言?

1 个答案:

答案 0 :(得分:1)

看起来很有效:

// Get the current text view.
IVsTextManager txtMgr = (IVsTextManager)GetService(typeof(SVsTextManager));
int mustHaveFocus = 1;//means true
txtMgr.GetActiveView(mustHaveFocus, null, out currentTextView);

userData = currentTextView as IVsUserData;
if (userData == null)// no text view 
{
    Console.WriteLine("No text view is currently open");
    return;
}

// In the next 4 statments, I am trying to get access to the editor's view 
object holder;
Guid guidViewHost = DefGuidList.guidIWpfTextViewHost;
userData.GetData(ref guidViewHost, out holder);
viewHost = (IWpfTextViewHost)holder;

// Get a snapshot of the current editor's text.
allText = viewHost.TextView.TextSnapshot.GetText();

// Get the language for the current editor.
string language = viewHost.TextViewtextView.TextDataModel.ContentType.TypeName;

这将返回VB.Net的“Basic”,这正是我需要知道的。