Reputation: 2703
How to copy/get the current line number in the active document of Visual Studio using C#
Upvotes: 0
Views: 1843
Reputation: 2703
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.
Upvotes: 2