VS 2010 addin: getting selected text in the editor
Coders, I am developing an add in for VS2010 and I am trying to get the selected text in the code editor. so far, i have been searching many webpages and thy all seems to use DTE.ActiveDocument which causes an error in my code. I have written two versions of a method that suppose to return a selected text in the editor but I still get the same error over and over: the error is: An object reference is required for the non-static field, method, or property 'EnvDTE._DTE.ActiveDocument.get' and here are my two versions of the method (only relevant code is showen):
using EnvDTE;
private string getSelectedText_V1()
{
string selectedText = string.Empty;
/*PROBLEM HERE: An object reference is required for the non-static field, method, or property 'EnvDTE._DTE.ActiveDocument.get'*/
Doc开发者_StackOverflow社区ument doc = DTE.ActiveDocument;
return selectedText;
}
private string getSelectedText_V2()
{
string selectedText = string.Empty;
/*PROBLEM HERE: An object reference is required for the non-static field, method, or property 'EnvDTE._DTE.ActiveDocument.get'*/
EnvDTE.TextSelection TxtSelection = DTE.ActiveDocument.Selection;
return selectedText;
}
Please help me figure out what i did wrong in my code?
If you have access to GetService() method in your addin, you could add:
DTE dte = this.GetService(typeof(DTE)) as DTE;
Then your code would become:
private string getSelectedText_V1()
{
string selectedText = string.Empty;
DTE dte = this.GetService(typeof(DTE)) as DTE;
Document doc = dte.ActiveDocument;
return doc.Selection.Text;
}
精彩评论