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.
Asked
Active
Viewed 1,567 times
1

oneManArmin
- 606
- 6
- 24
-
See https://stackoverflow.com/questions/32502847/is-there-any-extension-for-vs-copying-code-position – Sergey Vlasov Sep 02 '17 at 06:01
-
Can you provide an example as to how to use this? The first line of the example actually provided via the link, `EnvDTE.TextSelection ts = DTE.ActiveWindow.Selection as EnvDTE.TextSelection;` gives me the error: _An object reference is required for the non-static field, method, or property '_DTE.ActiveWindow'_. – oneManArmin Sep 02 '17 at 17:20
-
To get the DTE object see https://stackoverflow.com/questions/19087186/how-to-acquire-dte-object-instance-in-a-vs-package-project – Sergey Vlasov Sep 03 '17 at 04:05
-
I have create a sample based on Sergey Vlasov's suggestion and it could return the line number where the cursor on in code editor. You just need to get DTE value with "DTE dte = (DTE)this.ServiceProvider.GetService(typeof(DTE));" in VSIX project and replace the DTE.ActiveWindow to dte.ActiveWindow. If any question, please feel free to let us know. – Weiwei Sep 04 '17 at 07:27
-
Thank goes to both of you, it is working perfectly. If any of you converts the comments into a proper answer so that others might find it more easily, I'm happy to mark it as an answer/upvote! – oneManArmin Sep 05 '17 at 08:38
1 Answers
3
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);
}

Weiwei
- 3,674
- 1
- 10
- 13