2010-09-29 58 views
1

我是新來Visual Studio的構建插件,但已設法爲VS2010構建一個簡單的工具,在當前活動的代碼窗口中進行一些文本操作。我已經到了需要了解當前文本視圖的語言(VB.Net,C#或其他)的地步。語言在VS2010中的文本查看擴展

我試圖讓文件名(這樣我就可以看擴展名來確定語言)使用下面的代碼:

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

看起來是這樣工作的:

// 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,而這正是我需要知道。

+1

只是FYI,你應該儘量避免snapshot.GetText()。將緩衝區變成一個大的字符串比較昂貴(它存儲在「一棵樹」中,而不是作爲一個單一的字符串)。 – 2010-10-01 05:15:11

+0

@Noah:謝謝 - 這很好。 – Kramii 2010-10-01 08:49:48