1

我是为 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。有没有其他方法可以获取文件名/语言?

4

1 回答 1

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 返回“基本”,这正是我需要知道的。

于 2010-09-29T16:05:00.057 回答