Home Professional Edition Commands Extensions SSMS Resources What's New

Visual Commander Visual Commander

Commands

1. Open Visual Studio about dialog.

C#
public class C : VisualCommanderExt.ICommand
{
	public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
	{
		DTE.ExecuteCommand("Help.About");
	}
}
VB
Imports EnvDTE80
Imports Microsoft.VisualStudio.Shell
Imports VisualCommanderExt
Public Class C
	Implements ICommand
	Sub Run(DTE As DTE2, package As Package) Implements ICommand.Run
		DTE.ExecuteCommand("Help.About")
	End Sub
End Class

2. Move the caret to the beginning of the containing function.

VB
Imports EnvDTE
Imports EnvDTE80
Imports Microsoft.VisualStudio.Shell
Imports VisualCommanderExt
Public Class C
	Implements ICommand
	Sub Run(DTE As DTE2, package As Package) Implements ICommand.Run
		Dim textSelection As EnvDTE.TextSelection
		Dim codeElement As EnvDTE.CodeElement
		textSelection = DTE.ActiveWindow.Selection
		Try
			codeElement = textSelection.ActivePoint.CodeElement(
				vsCMElement.vsCMElementFunction)
			If Not (codeElement Is Nothing) Then
				textSelection.MoveToPoint(codeElement.GetStartPoint(
					vsCMPart.vsCMPartHeader))
			End If
		Catch
		End Try
	End Sub
End Class

3. Copy to the clipboard properties of the selected class in Visual Studio text editor.

C#
using EnvDTE;
using EnvDTE80;
public class C : VisualCommanderExt.ICommand
{
	public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
	{
		EnvDTE.TextSelection ts = DTE.ActiveWindow.Selection as EnvDTE.TextSelection;
		if (ts == null)
			return;
		EnvDTE.CodeClass codeClass = ts.ActivePoint.CodeElement[vsCMElement.vsCMElementClass]
			as EnvDTE.CodeClass;
		if (codeClass == null)
			return;
		string properties = "";
		foreach (CodeElement elem in codeClass.Members)
		{
			if (elem.Kind == vsCMElement.vsCMElementProperty)
				properties += elem.Name + System.Environment.NewLine;
		}
		System.Windows.Clipboard.SetText(properties);
	}
}

4. Toggle line numbers for C# files.

VB
Imports EnvDTE80
Imports Microsoft.VisualStudio.Shell
Imports VisualCommanderExt
Public Class C
	Implements ICommand
	Sub Run(DTE As DTE2, package As Package) Implements ICommand.Run
		dim v = DTE.Properties("TextEditor", "CSharp").Item("ShowLineNumbers").Value
		DTE.Properties("TextEditor", "CSharp").Item("ShowLineNumbers").Value = Not v
	End Sub
End Class

5. Insert date and time.

VB
Imports EnvDTE80
Imports Microsoft.VisualStudio.Shell
Imports VisualCommanderExt
Public Class C
	Implements ICommand
	Sub Run(DTE As DTE2, package As Package) Implements ICommand.Run
		Dim textSelection As EnvDTE.TextSelection
		textSelection = CType(DTE.ActiveDocument.Selection(), EnvDTE.TextSelection)
		textSelection.Text = System.DateTime.Now.ToLongDateString() + " " + 
			System.DateTime.Now.ToLongTimeString()	
	End Sub
End Class
VB
Imports EnvDTE
Imports EnvDTE80
Imports Microsoft.VisualStudio.Shell
Imports Microsoft.VisualBasic
Imports VisualCommanderExt
Public Class C
	Implements ICommand
	Sub Run(DTE As DTE2, package As Package) Implements ICommand.Run
		Dim window As Window
		Dim textSelection As TextSelection
		Dim textSelectionPointSaved As TextPoint
		Dim outputWindowPane As OutputWindowPane
		Dim findResult As EnvDTE.vsFindResult
		Dim textDocument As EnvDTE.TextDocument
		Dim lastFoundAt As Integer = 0
		textDocument = DTE.ActiveDocument.Object("TextDocument")
		textSelection = textDocument.Selection
		window = DTE.ActiveDocument.Windows.Item(1)
		PrepareDefaultFind(DTE, "List Matching Lines")
		'' Set up output window pane and loop until no more matches.
		outputWindowPane = GetOutputWindowPane(DTE, "Matching Lines")
		textSelection.StartOfDocument()
		textSelectionPointSaved = textSelection.ActivePoint.CreateEditPoint()
		''GetOutputWindowPane activates Output Window, so re-activate our window.
		window.Activate()
		outputWindowPane.Clear()
		CType(DTE.Find, EnvDTE80.Find2).WaitForFindToComplete = True
		findResult = DTE.Find.Execute()
		While (findResult = vsFindResult.vsFindResultFound)
			If textSelection.AnchorPoint.Line <= lastFoundAt Then
				Exit While
			End If
			textSelection.SelectLine()
			outputWindowPane.OutputString("line " + 
				textSelection.AnchorPoint.Line.ToString() + ": " + textSelection.Text)
			lastFoundAt = textSelection.AnchorPoint.Line
			textSelection.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn)
			findResult = DTE.Find.Execute()
		End While
		'' Restore caret to location before invoking this command.
		textSelection.MoveToPoint(textSelectionPointSaved)
	End Sub
	Function PrepareDefaultFind(DTE As DTE2, ByVal prompt As String) As String
		Dim what As String
		DTE.Find.MatchWholeWord = False
		DTE.Find.Action = vsFindAction.vsFindActionFind
		DTE.Find.Target = vsFindTarget.vsFindTargetCurrentDocument
		DTE.Find.MatchCase = False
		DTE.Find.Backwards = False
		DTE.Find.MatchInHiddenText = True
		DTE.Find.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxLiteral
		what = InputBox(prompt)
		If (what <> "") Then
			DTE.Find.FindWhat = what
		End If
		Return what
	End Function
	Function GetOutputWindowPane(DTE As DTE2, ByVal Name As String) As OutputWindowPane
		Dim window As Window
		Dim outputWindow As OutputWindow
		Dim outputWindowPane As OutputWindowPane
		window = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput)
		window.Visible = True
		outputWindow = window.Object
		Try
			outputWindowPane = outputWindow.OutputWindowPanes.Item(Name)
		Catch e As System.Exception
			outputWindowPane = outputWindow.OutputWindowPanes.Add(Name)
		End Try
		outputWindowPane.Activate()
		Return outputWindowPane
	End Function
End Class

7. Browse one folder up in Sorce Control Explorer.

C#
References: Microsoft.VisualStudio.TeamFoundation.VersionControl
public class C : VisualCommanderExt.ICommand
{
	public void Run(EnvDTE80.DTE2 DTE_, Microsoft.VisualStudio.Shell.Package package) 
	{
		DTE = DTE_;
		string path = GetSelectedFolderPath();
		if (path == null)
			return;
		int i = path.LastIndexOf('/');
		if (i < 1 || i == path.Length - 1)
			return;
		if (i == 1)
			i = 2;
		string upFolderPath = path.Remove(i);
		SelectFolder(upFolderPath);
	}
	public string GetSelectedFolderPath()
        {
            Microsoft.VisualStudio.TeamFoundation.VersionControl.VersionControlExplorerExt explorer =
                GetSourceControlExplorer();
            if (explorer == null)
                return null;
            if (explorer.CurrentFolderItem == null)
                return null;
            return explorer.CurrentFolderItem.SourceServerPath;
        }
        public void SelectFolder(string path)
        {
            Microsoft.VisualStudio.TeamFoundation.VersionControl.VersionControlExplorerExt explorer =
                GetSourceControlExplorer();
            if (explorer != null)
                explorer.Navigate(path);
        }
        private Microsoft.VisualStudio.TeamFoundation.VersionControl.VersionControlExplorerExt 
		GetSourceControlExplorer()
        {
            Microsoft.VisualStudio.TeamFoundation.VersionControl.VersionControlExt versionControl =
                DTE.GetObject("Microsoft.VisualStudio.TeamFoundation.VersionControl.VersionControlExt")
			as Microsoft.VisualStudio.TeamFoundation.VersionControl.VersionControlExt;
            if (versionControl == null)
                return null;
            return versionControl.Explorer;
        }
	private EnvDTE80.DTE2 DTE;
}

8. Show mnemonics in .rc dialog designer.

Download vcmd

C#
public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
    {
        Interop.EnumChildWindows((System.IntPtr)DTE.MainWindow.HWnd, WindowEnumProc, 0);
    }
    public static bool WindowEnumProc(System.IntPtr hwnd, int lParam) 
    {
        System.IntPtr p = Interop.GetParent(hwnd);
        if (GetClassName(p) == "#32770")
        {
            System.UInt32 WM_UPDATEUISTATE = 0x0128;
            int UISF_HIDEACCEL = 2;
            int UIS_INITIALIZE = 3;
            Interop.SendMessage(hwnd, WM_UPDATEUISTATE, 
		(System.IntPtr)(UISF_HIDEACCEL | (UIS_INITIALIZE << 16)), System.IntPtr.Zero);
        }
        return true;
    }
    public static string GetClassName(System.IntPtr wnd)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Capacity = 256;
        Interop.GetClassName(wnd, sb, sb.Capacity);
        return sb.ToString();
    }
}
class Interop
{
    public delegate bool WindowEnumDelegate(System.IntPtr hwnd, int lParam);
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    public static extern int EnumChildWindows(System.IntPtr hwnd,
                                              WindowEnumDelegate del,
                                              int lParam);
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    static public extern int GetClassName(System.IntPtr hwnd, System.Text.StringBuilder lpClassName, 
	int nMaxCount);
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    public static extern System.IntPtr GetParent(System.IntPtr hWnd);
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    public static extern System.IntPtr SendMessage(System.IntPtr hWnd, System.UInt32 Msg, 
	System.IntPtr wParam, System.IntPtr lParam);
}
Mnemonics

9. Attach to specific process.

Attach to specific Process shortcut in Visual Studio by Mark Vincze.

10. Run GoToDefinition via IVsUIShell.

VB
Imports EnvDTE80
Imports Microsoft.VisualStudio.Shell
Imports VisualCommanderExt
Public Class C
	Implements ICommand
	Sub Run(DTE As DTE2, package As Package) Implements ICommand.Run
		Dim cmd As EnvDTE.Command
		Dim shell As Microsoft.VisualStudio.Shell.Interop.IVsUIShell
		Dim arg As Object
		Dim guid As System.Guid
		Dim serviceProvider As System.IServiceProvider
		serviceProvider = New Microsoft.VisualStudio.Shell.ServiceProvider(
		           CType(DTE, Microsoft.VisualStudio.OLE.Interop.IServiceProvider))
		shell = serviceProvider.GetService(GetType(Microsoft.VisualStudio.Shell.Interop.SVsUIShell))
		cmd = DTE.Commands.Item("Edit.GoToDefinition", 0)
		guid = New System.Guid(cmd.Guid)
		shell.PostExecCommand(guid, cmd.ID, 0, arg)
	End Sub
End Class

11. Debug specific project.

VB
Imports EnvDTE80
Imports Microsoft.VisualStudio.Shell
Imports VisualCommanderExt
Public Class C
	Implements ICommand
	Sub Run(DTE As DTE2, package As Package) Implements ICommand.Run
		DTE.Windows.Item(EnvDTE.Constants.vsWindowKindSolutionExplorer).Activate()
		DTE.ActiveWindow.Object.GetItem("MySolution\MyProject").Select(vsUISelectionType.vsUISelectionTypeSelect)
		DTE.ExecuteCommand("ClassViewContextMenus.ClassViewProject.Debug.Startnewinstance")
	End Sub
End Class

12. Toggle CodeLens on/off.

VB
Imports EnvDTE80
Imports Microsoft.VisualStudio.Shell
Imports VisualCommanderExt
Public Class C
	Implements ICommand
	Sub Run(DTE As DTE2, package As Package) Implements ICommand.Run
            DTE.ExecuteCommand("EditorContextMenus.CodeLens.CodeLensOptions")
            System.Threading.Thread.Sleep(300)
            System.Windows.Forms.SendKeys.Send("{TAB} {ENTER}")
	End Sub
End Class

13. Copy current file, line, method.

C#
using EnvDTE;
using EnvDTE80;
public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
    {
        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 result = DTE.ActiveWindow.Document.FullName + System.Environment.NewLine +
		  "Line " + ts.CurrentLine + System.Environment.NewLine +
		  func.FullName;
        System.Windows.Clipboard.SetText(result);
    }
}

14. Block comment.

C#
using EnvDTE;
using EnvDTE80;
public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
    {
        EnvDTE.TextSelection ts = DTE.ActiveDocument.Selection as EnvDTE.TextSelection;
        ts.Text = "/* " + ts.Text + " */";
    }
}

15. Set font size.

VB
Imports EnvDTE80
Imports Microsoft.VisualStudio.Shell
Imports VisualCommanderExt
Public Class C
	Implements ICommand
	Sub Run(DTE As DTE2, package As Package) Implements ICommand.Run
            DTE.Properties("FontsAndColors", "TextEditor").Item("FontSize").Value = 20
	End Sub
End Class

16. Close the current document tab and activate next.

C#
using EnvDTE;
using EnvDTE80;
public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
    {
	dte = DTE;
	if (IsCommandAvailable("Window.NextTab"))
	{
		EnvDTE.Window w = DTE.ActiveWindow;
		DTE.ExecuteCommand("Window.NextTab");
		w.Close();
	}
	else if (IsCommandAvailable("File.Close"))
		DTE.ExecuteCommand("File.Close");
    }
    private bool IsCommandAvailable(string commandName)
    {
        EnvDTE80.Commands2 commands = dte.Commands as EnvDTE80.Commands2;
        if (commands == null)
            return false;
        EnvDTE.Command command = commands.Item(commandName, 0);
        if (command == null)
            return false;
        return command.IsAvailable;
    }
    private EnvDTE80.DTE2 dte;
}

17. Use Roslyn.

C#

References:
c:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\PrivateAssemblies\Microsoft.CodeAnalysis.dll
c:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\PrivateAssemblies\Microsoft.CodeAnalysis.CSharp.dll
System.Runtime
System.Text.Encoding
System.Threading.Tasks
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
public class C : VisualCommanderExt.ICommand
{
	public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
	{
		SyntaxTree tree = CSharpSyntaxTree.ParseText(
		@"using System;
		using System.Collections.Generic;
		using System.Text;
		namespace HelloWorld
		{
		class Program
		{
		static void Main(string[] args)
		{
		Console.WriteLine(""Hello, World!"");
		}
		}
		}");
		var root = (CompilationUnitSyntax)tree.GetRoot();
		System.Windows.MessageBox.Show("using[1] - " + root.Usings[1].Name.ToString());
	}
}

18. Create a typed variable from the current method invocation.

C#

References:
Microsoft.VisualStudio.TextManager.Interop
Microsoft.VisualStudio.Editor
Microsoft.VisualStudio.Text.UI.Wpf
Microsoft.VisualStudio.Text.UI
Microsoft.VisualStudio.CoreUtility
Microsoft.VisualStudio.ComponentModelHost
Microsoft.VisualStudio.Text.Data
c:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\PrivateAssemblies\Microsoft.CodeAnalysis.EditorFeatures.Text.dll
c:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\PrivateAssemblies\Microsoft.CodeAnalysis.dll
c:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\PrivateAssemblies\Microsoft.CodeAnalysis.CSharp.dll
c:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\PrivateAssemblies\Microsoft.CodeAnalysis.Workspaces.dll
System.Runtime
System.Text.Encoding
System.Threading.Tasks
System.Collections.Immutable
System.Core
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using System.Linq;
public class C : VisualCommanderExt.ICommand
{
	public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
	{
		serviceProvider = package as System.IServiceProvider;
		Microsoft.VisualStudio.Text.Editor.IWpfTextView textView = GetTextView();
		Microsoft.VisualStudio.Text.SnapshotPoint caretPosition = textView.Caret.Position.BufferPosition;
		Microsoft.CodeAnalysis.Document document = caretPosition.Snapshot.GetOpenDocumentInCurrentContextWithChanges();
		Microsoft.CodeAnalysis.CSharp.Syntax.InvocationExpressionSyntax invocationExpressionNode = 
			document.GetSyntaxRootAsync().Result.FindToken(caretPosition).Parent.AncestorsAndSelf().
				OfType<Microsoft.CodeAnalysis.CSharp.Syntax.InvocationExpressionSyntax>().FirstOrDefault();
		if (invocationExpressionNode != null)
		{
			Microsoft.CodeAnalysis.SemanticModel semanticModel = document.GetSemanticModelAsync().Result;
			Microsoft.CodeAnalysis.IMethodSymbol methodSymbol = 
				semanticModel.GetSymbolInfo(invocationExpressionNode).Symbol as 
					Microsoft.CodeAnalysis.IMethodSymbol;
			textView.TextBuffer.Insert(invocationExpressionNode.SpanStart, 
				methodSymbol.ReturnType.ToString() + " v = ");
		}
	}
	private Microsoft.VisualStudio.Text.Editor.IWpfTextView GetTextView()
	{
		Microsoft.VisualStudio.TextManager.Interop.IVsTextManager textManager = 
			(Microsoft.VisualStudio.TextManager.Interop.IVsTextManager)serviceProvider.GetService(
				typeof(Microsoft.VisualStudio.TextManager.Interop.SVsTextManager));
		Microsoft.VisualStudio.TextManager.Interop.IVsTextView textView;
		textManager.GetActiveView(1, null, out textView);
		return GetEditorAdaptersFactoryService().GetWpfTextView(textView);
	}
	private Microsoft.VisualStudio.Editor.IVsEditorAdaptersFactoryService GetEditorAdaptersFactoryService()
	{
		Microsoft.VisualStudio.ComponentModelHost.IComponentModel componentModel =
			(Microsoft.VisualStudio.ComponentModelHost.IComponentModel)serviceProvider.GetService(
				typeof(Microsoft.VisualStudio.ComponentModelHost.SComponentModel));
		return componentModel.GetService<Microsoft.VisualStudio.Editor.IVsEditorAdaptersFactoryService>();
	}
	private System.IServiceProvider serviceProvider;
}
	
Created typed variables

19. Clear tracked changes (green bar) for the current document (by reloading it).

C#
public class C : VisualCommanderExt.ICommand
{
	public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
	{
		serviceProvider = package as System.IServiceProvider;
		Reload(DTE.ActiveDocument.FullName);
	}
    private void Reload(string file)
    {
        Microsoft.VisualStudio.Shell.Interop.IVsRunningDocumentTable rdt =
            (Microsoft.VisualStudio.Shell.Interop.IVsRunningDocumentTable)serviceProvider.GetService(
                 typeof(Microsoft.VisualStudio.Shell.Interop.SVsRunningDocumentTable));
        Microsoft.VisualStudio.Shell.Interop.IVsHierarchy h;
        System.UInt32 id;
        System.IntPtr data;
        System.UInt32 cookie;
        Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument(
            (uint)Microsoft.VisualStudio.Shell.Interop._VSRDTFLAGS.RDT_NoLock,
            file,
            out h,
            out id,
            out data,
            out cookie));
        try
        {
            Microsoft.VisualStudio.Shell.Interop.IVsPersistDocData persistDocData =
                (Microsoft.VisualStudio.Shell.Interop.IVsPersistDocData)
                    System.Runtime.InteropServices.Marshal.GetObjectForIUnknown(data);
            {
                int dirty;
                Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(persistDocData.IsDocDataDirty(out dirty));
                if (dirty != 0)
                    return;
            }
            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(persistDocData.ReloadDocData(
                (uint)Microsoft.VisualStudio.Shell.Interop._VSRELOADDOCDATA.RDD_RemoveUndoStack));
        }
        finally
        {
            System.Runtime.InteropServices.Marshal.Release(data);
        }
    }
    private System.IServiceProvider serviceProvider;
}
	

20. Copy the list of installed Visual Studio extensions to the clipboard.

C#

References for VS 2015:
Microsoft.VisualStudio.ExtensionManager
References for VS 2017:
Microsoft.VisualStudio.ExtensionManager
..\Microsoft.VisualStudio.ExtensionEngine
public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
    {
        System.IServiceProvider serviceProvider = package as System.IServiceProvider;
        Microsoft.VisualStudio.ExtensionManager.IVsExtensionManager em =
           (Microsoft.VisualStudio.ExtensionManager.IVsExtensionManager)serviceProvider.GetService(
                typeof(Microsoft.VisualStudio.ExtensionManager.SVsExtensionManager));
	
        string result = "";
        foreach(Microsoft.VisualStudio.ExtensionManager.IInstalledExtension i in em.GetInstalledExtensions())
        {
            Microsoft.VisualStudio.ExtensionManager.IExtensionHeader h = i.Header;
            if (!h.SystemComponent)
                result += h.Name + " (by " + h.Author + ") v" + h.Version + " " + h.MoreInfoUrl + System.Environment.NewLine;
        }
        System.Windows.Clipboard.SetText(result);
    }
}
	

21. Turn IntelliSense off for the duration of macro recording.

C#
public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
    {
        EnvDTE.Properties p = DTE.get_Properties("TextEditor", "CSharp");
        bool startingMacroRecording = (bool)p.Item("BraceCompletion").Value == true;
        bool useIntellisense = startingMacroRecording ? false : true;
        p.Item("BraceCompletion").Value = useIntellisense;
        p.Item("AutoListMembers").Value = useIntellisense;
        DTE.ExecuteCommand("VCmd.RecordMacro");
    }
}
	

22. Open a file from a relative path in a comment.

C#
public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
    {
        EnvDTE.TextSelection ts = DTE.ActiveDocument.Selection as EnvDTE.TextSelection;
        string relativePath = ts.Text;
        string absolutePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(DTE.Solution.FileName), relativePath);
        DTE.ItemOperations.OpenFile(absolutePath, null);
    }
}
	

23. Restart Visual Studio with the current solution.

C#
public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
    {
		string vs = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
		string solution = DTE.Solution.FullName;
		DTE.ExecuteCommand("File.SaveAll");
		DTE.ExecuteCommand("File.Exit");
		System.Diagnostics.Process.Start(vs, '"' + solution + '"');
    }
}
	

24. Copy selected variable value to the clipboard during debugging.

C#
public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
    {
		EnvDTE.TextSelection ts = DTE.ActiveWindow.Selection as EnvDTE.TextSelection;
		string variableName = ts.Text;
		EnvDTE.Expression exp = DTE.Debugger.GetExpression(variableName);
		string value = exp.Value;
		System.Windows.Clipboard.SetText(value);
    }
}
	

25. Run custom tool for each file in the selected Solution Explorer folder.

C#

References:
VSLangProj
public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
    {
        this.DTE = DTE;
        foreach (EnvDTE.UIHierarchyItem i in GetSelectedSolutionExplorerItem().UIHierarchyItems)
            RunCustomTool(i);
    }

    private EnvDTE.UIHierarchyItem GetSelectedSolutionExplorerItem()
    {
        EnvDTE.UIHierarchy solutionExplorer = DTE.ToolWindows.SolutionExplorer;
        object[] items = solutionExplorer.SelectedItems as object[];
        if (items.Length != 1)
            return null;

        return items[0] as EnvDTE.UIHierarchyItem;
    }

    private void RunCustomTool(EnvDTE.UIHierarchyItem item)
    {
        EnvDTE.ProjectItem projectItem = item.Object as EnvDTE.ProjectItem;
        if (projectItem != null)
        {
            VSLangProj.VSProjectItem vsProjectItem = projectItem.Object as VSLangProj.VSProjectItem;
            if (vsProjectItem != null)
                vsProjectItem.RunCustomTool();
        }
    }

    EnvDTE80.DTE2 DTE;
}
	

26. Add # to the beginning of the current line or selected lines.

C#
public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package)
{
	EnvDTE.TextSelection ts = DTE.ActiveDocument.Selection as EnvDTE.TextSelection;
	EnvDTE.TextDocument doc = DTE.ActiveDocument.Object("TextDocument") as EnvDTE.TextDocument;
	EnvDTE.EditPoint p = doc.CreateEditPoint();
	for (int i = ts.TopLine; i <= ts.BottomLine; ++i)
	{
		p.MoveToLineAndOffset(i, 1);
		p.Insert("#");
	}
}

28. Paste text from the clipboard without any reformatting.

C#
public class C : VisualCommanderExt.ICommand
{
	public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
	{
		EnvDTE.TextSelection ts = DTE.ActiveWindow.Selection as EnvDTE.TextSelection;
		ts.Insert(System.Windows.Clipboard.GetText());
	}
}

29. Scroll the current text editor view horizontally left or right.

Download vcmd

C#

References:
Microsoft.VisualStudio.Text.UI
Microsoft.VisualStudio.Text.UI.Wpf
Microsoft.VisualStudio.CoreUtility
Microsoft.VisualStudio.TextManager.Interop
Microsoft.VisualStudio.Editor
Microsoft.VisualStudio.ComponentModelHost
public class C : VisualCommanderExt.ICommand
{
	public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
	{
        serviceProvider = package as System.IServiceProvider;
        Microsoft.VisualStudio.Text.Editor.IWpfTextView textView = GetTextView();
        textView.ViewportLeft += 12; // Scroll right
      //textView.ViewportLeft -= 12; // Scroll left
    }

    private Microsoft.VisualStudio.Text.Editor.IWpfTextView GetTextView()
    {
        Microsoft.VisualStudio.TextManager.Interop.IVsTextManager textManager =
            (Microsoft.VisualStudio.TextManager.Interop.IVsTextManager)serviceProvider.GetService(
                typeof(Microsoft.VisualStudio.TextManager.Interop.SVsTextManager));
        Microsoft.VisualStudio.TextManager.Interop.IVsTextView textView;
        textManager.GetActiveView(1, null, out textView);
        return GetEditorAdaptersFactoryService().GetWpfTextView(textView);
    }

    private Microsoft.VisualStudio.Editor.IVsEditorAdaptersFactoryService GetEditorAdaptersFactoryService()
    {
        Microsoft.VisualStudio.ComponentModelHost.IComponentModel componentModel =
            (Microsoft.VisualStudio.ComponentModelHost.IComponentModel)serviceProvider.GetService(
                typeof(Microsoft.VisualStudio.ComponentModelHost.SComponentModel));
        return componentModel.GetService();
    }

    private System.IServiceProvider serviceProvider;
}

30. Open the Fonts and Colors options page.

C#

References:
System.Design
public class C : VisualCommanderExt.ICommand
{
	public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
	{
		string fontsAndColorsGUID = "57F6B7D2-1436-11D1-883C-0000F87579D2";
		var command = new System.ComponentModel.Design.CommandID(
			Microsoft.VisualStudio.VSConstants.GUID_VSStandardCommandSet97,
			Microsoft.VisualStudio.VSConstants.cmdidToolsOptions);
		var serviceProvider = package as System.IServiceProvider;
		var mcs = (Microsoft.VisualStudio.Shell.OleMenuCommandService)serviceProvider.GetService(
			typeof(System.ComponentModel.Design.IMenuCommandService));
		mcs.GlobalInvoke(command, fontsAndColorsGUID);
	}
}

31. Create a view model property.

C# 4

References:
Microsoft.VisualBasic
public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package)
    {
        string propertyName = Microsoft.VisualBasic.Interaction.InputBox("Property name", "Create view model property [1/2]", 
					"Foo", -1, -1);
        string propertyType = Microsoft.VisualBasic.Interaction.InputBox("Property type", "Create view model property [2/2]", 
					"double", -1, -1);
        string fieldName = "_" + System.Char.ToLower(propertyName[0]) + propertyName.Substring(1);
        string snippet = @"
private {1} {2};
public {1} {0}
{{
   get {{ return {2}; }}
   set {{ SetProperty(ref {2}, value); }}
}}
";
        EnvDTE.TextSelection ts = DTE.ActiveDocument.Selection as EnvDTE.TextSelection;
        ts.Text = string.Format(snippet, propertyName, propertyType, fieldName);
    }
}
C# 6

References:
Microsoft.VisualBasic
public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package)
    {
        string propertyName = Microsoft.VisualBasic.Interaction.InputBox("Property name", "Create view model property [1/2]", 
					"Foo", -1, -1);
        string propertyType = Microsoft.VisualBasic.Interaction.InputBox("Property type", "Create view model property [2/2]", 
					"double", -1, -1);
        string fieldName = "_" + System.Char.ToLower(propertyName[0]) + propertyName.Substring(1);

        EnvDTE.TextSelection ts = DTE.ActiveDocument.Selection as EnvDTE.TextSelection;
        ts.Text = $@"
private {propertyType} {fieldName};
public {propertyType} {propertyName}
{{
   get {{ return {fieldName}; }}
   set {{ SetProperty(ref {fieldName}, value); }}
}}
";
    }
}

32. Insert GUID.

C#
public class C : VisualCommanderExt.ICommand
{
	public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
	{
		EnvDTE.TextSelection ts = DTE.ActiveDocument.Selection as EnvDTE.TextSelection;
		ts.Text = System.Guid.NewGuid().ToString();
	}
}

33. Change find result format to remove the full path.

See Customize how Find in Files results are displayed in the Find Results Window for more information.

(Works with private VS 2017 registry as well.)

C#
public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
    {
        var key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(
            @"Software\Microsoft\VisualStudio\" + DTE.Version + @"\Find");
        key.SetValue("Find result format", @"$f$e($l): $t\r\n");
    }
}

34. Insert text into the current active text view.

C#

References:
Microsoft.VisualStudio.TextManager.Interop
Microsoft.VisualStudio.Editor
Microsoft.VisualStudio.Text.UI.Wpf
Microsoft.VisualStudio.Text.UI
Microsoft.VisualStudio.CoreUtility
Microsoft.VisualStudio.ComponentModelHost
Microsoft.VisualStudio.Text.Data
public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
    {
        serviceProvider = package as System.IServiceProvider;
        Microsoft.VisualStudio.Text.Editor.IWpfTextView textView = GetTextView();
        Microsoft.VisualStudio.Text.SnapshotPoint caretPosition = textView.Caret.Position.BufferPosition;
        textView.TextBuffer.Insert(caretPosition.Position, "sample code");
    }

    private Microsoft.VisualStudio.Text.Editor.IWpfTextView GetTextView()
    {
        Microsoft.VisualStudio.TextManager.Interop.IVsTextManager textManager =
            (Microsoft.VisualStudio.TextManager.Interop.IVsTextManager)serviceProvider.GetService(
                typeof(Microsoft.VisualStudio.TextManager.Interop.SVsTextManager));
        Microsoft.VisualStudio.TextManager.Interop.IVsTextView textView;
        textManager.GetActiveView(1, null, out textView);
        return GetEditorAdaptersFactoryService().GetWpfTextView(textView);
    }

    private Microsoft.VisualStudio.Editor.IVsEditorAdaptersFactoryService GetEditorAdaptersFactoryService()
    {
        Microsoft.VisualStudio.ComponentModelHost.IComponentModel componentModel =
            (Microsoft.VisualStudio.ComponentModelHost.IComponentModel)serviceProvider.GetService(
                typeof(Microsoft.VisualStudio.ComponentModelHost.SComponentModel));
        return componentModel.GetService();
    }

    private System.IServiceProvider serviceProvider;
}

35. Go to a member in the current document (VS 2017).

Download vcmd

C#
public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
    {
        serviceProvider = package as System.IServiceProvider;
        SetSearchCurrentDocument(true);
        DTE.ExecuteCommand("Edit.GoToMember");
    }

    private void SetSearchCurrentDocument(bool value)
    {
        System.Type t = serviceProvider.GetService(typeof(SVsNavigateToService)).
            GetType().Assembly.GetType("Microsoft.VisualStudio.PlatformUI.NavigateToSettings");
        object o = t.GetProperty("Instance",
            System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static).
            GetValue(null);
        t.GetProperty("SearchCurrentDocument",
            System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).
            SetValue(o, value);
    }

    private System.IServiceProvider serviceProvider;
}

[System.Runtime.InteropServices.Guid("65C44EF9-16F8-4F36-BD73-F10335EC452E")]
public interface SVsNavigateToService
{
}
Go to a member

36. Go to a file in the solution (VS 2017).

Download vcmd

C#
public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
    {
        serviceProvider = package as System.IServiceProvider;
        SetSearchCurrentDocument(false);
        DTE.ExecuteCommand("Edit.GoToFile");
    }

    private void SetSearchCurrentDocument(bool value)
    {
        System.Type t = serviceProvider.GetService(typeof(SVsNavigateToService)).
            GetType().Assembly.GetType("Microsoft.VisualStudio.PlatformUI.NavigateToSettings");
        object o = t.GetProperty("Instance",
            System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static).
            GetValue(null);
        t.GetProperty("SearchCurrentDocument",
            System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).
            SetValue(o, value);
    }

    private System.IServiceProvider serviceProvider;
}

[System.Runtime.InteropServices.Guid("65C44EF9-16F8-4F36-BD73-F10335EC452E")]
public interface SVsNavigateToService
{
}
Go to a file

37. Show the GUID and ID of menu or command when Ctrl+Shift is pressed.

See Using EnableVSIPLogging to identify menus and commands for more information.

(Works with private VS 2017 registry as well.)

C#
public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
    {
        var key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(
            @"Software\Microsoft\VisualStudio\" + DTE.Version + @"\General");
        key.SetValue("EnableVSIPLogging", 1);
    }
}
After running this command, a restart of Visual Studio is required.

38. Hide class info in Solution Explorer.

See Hide class info in Visual Studio Solution Explorer for more information.

(Works with private VS 2017 registry as well.)

C#
public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
    {
        var key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(
            @"Software\Microsoft\VisualStudio\" + DTE.Version);
        key.SetValue("UseSolutionNavigatorGraphProvider", 0);
    }
}
After running this command, a restart of Visual Studio is required.

39. Clone the current line.

C#
public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
    {
        DTE.ExecuteCommand("Edit.Copy");
        DTE.ExecuteCommand("Edit.Paste");
    }
}

40. Select the current function definition.

C#
public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
    {
        EnvDTE.TextSelection ts = DTE.ActiveDocument.Selection as EnvDTE.TextSelection;
        if (ts == null)
            return;
        EnvDTE.CodeFunction func = ts.ActivePoint.CodeElement[EnvDTE.vsCMElement.vsCMElementFunction] as EnvDTE.CodeFunction;
        if (func == null)
            return;
        ts.MoveToPoint(func.GetStartPoint(EnvDTE.vsCMPart.vsCMPartHeader));
        ts.MoveToPoint(func.GetEndPoint(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes), true);
    }
}