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

1.6k views Asked by At

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

There are 1 answers

0
Weiwei On BEST ANSWER

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