开发者

VS 2010 addin: getting selected text in the editor

开发者 https://www.devze.com 2023-02-06 00:37 出处:网络
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

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消