How to copy/get the current line number in the active document of Visual Studio using C#
Asked
Active
Viewed 1,598 times
0
-
See https://stackoverflow.com/questions/32502847/is-there-any-extension-for-vs-copying-code-position – Sergey Vlasov Jul 25 '17 at 03:36
-
@Sergey Vlasov: Oh, sorry, I didn't know that this question was answered - I had searched but couldn't find. – 123iamking Jul 25 '17 at 03:40
1 Answers
2
First of all, you need to add references "envDTE" and "envDTE80" for your C# project.
Then use the following code (I put it into click button event in my case) to copy the line number (and the file name) into clipboard.
private void btnGetLineVS_Click(object sender, EventArgs e)
{
EnvDTE80.DTE2 dte2;
dte2 = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE");
dte2.MainWindow.Activate();
int line = ((EnvDTE.TextSelection)dte2.ActiveDocument.Selection).ActivePoint.Line;
//Show it to the user the way you like
StringBuilder builder = new StringBuilder();
builder.Append(dte2.ActiveDocument.FullName);//The file name
builder.Append('\t');
builder.Append(line);//The current line
if (builder.Length > 0)
{
Clipboard.SetText(builder.ToString());
MessageBox.Show("Copied to clipboard");
}
else
MessageBox.Show("Nothing!");
}
Thanks to Reder's answer that I know this kind of thing exist, I always thought to do this, we have to use VSIX Visual Studio code project.

123iamking
- 2,387
- 4
- 36
- 56