问题
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