Visual Studio扩展:如何获取在其上调用上下文菜单的行?

Visual Studio扩展:如何获取在其上调用上下文菜单的行?

问题描述:

我想创建一个VS扩展名,在其中我需要知道菜单被调用的行号。我找到了 VisualBasic实现,其中包含一个似乎的宏>为此,但是我不知道如何在C#中启动它。目的是知道调用 ContextMenu 的确切行号,以便在其上放置一个占位符图标,就像断点一样。感谢您提供有用的链接,因为我在该主题上找不到太多内容。

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.

您可以创建VSIX项目并添加命令项目中的项目。然后在MenuItemCallback()方法中添加以下代码以获取代码行号。

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