Visual Studio Extension: How to get the line on which Context Menu was called?

会有一股神秘感。 提交于 2019-12-08 05:22:55

问题


I would like to create a VS extension in which I need to know the line number the menu was called on. I found a VisualBasic implementation with a macro that seems to do this, but I don't know how to start this in C#. The goal would be to know the exact number of the line the ContextMenu was called on to put a placeholder icon on it just like a break point. Useful links are appreciated since I couldn't find much on this topic.


回答1:


You could create a VSIX project and add a Command item in your project. Then add following code in MenuItemCallback() method to get the code line number.

    private void MenuItemCallback(object sender, EventArgs e)
    {
        EnvDTE.DTE dte = (EnvDTE.DTE)this.ServiceProvider.GetService(typeof(EnvDTE.DTE));

        EnvDTE.TextSelection ts = dte.ActiveWindow.Selection as EnvDTE.TextSelection;
        if (ts == null)
            return;
        EnvDTE.CodeFunction func = ts.ActivePoint.CodeElement[vsCMElement.vsCMElementFunction]
                    as EnvDTE.CodeFunction;
        if (func == null)
            return;

        string message = dte.ActiveWindow.Document.FullName + System.Environment.NewLine +
          "Line " + ts.CurrentLine + System.Environment.NewLine +
          func.FullName;

        string title = "GetLineNo";

        VsShellUtilities.ShowMessageBox(
            this.ServiceProvider,
            message,
            title,
            OLEMSGICON.OLEMSGICON_INFO,
            OLEMSGBUTTON.OLEMSGBUTTON_OK,
            OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
    }


来源:https://stackoverflow.com/questions/46006614/visual-studio-extension-how-to-get-the-line-on-which-context-menu-was-called

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