VS 2010 addin: getting selected text in the editor

限于喜欢 提交于 2019-12-06 13:33:54

问题


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'*/
        Document 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?


回答1:


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


来源:https://stackoverflow.com/questions/4772175/vs-2010-addin-getting-selected-text-in-the-editor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!