/vs-extensibility-skills:intercepting-commandsfrom vs-extensibility-skills
Intercepts existing Visual Studio commands to run custom logic before, after, or instead of the default handler. Covers VSIX Community Toolkit and VSSDK approaches.
Ships in vs-extensibility-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Command interception lets you run custom logic before, after, or instead of a built-in or third-party Visual Studio command. Common scenarios:
Interception is powerful but invasive — you're inserting your code into Visual Studio's own command pipeline. A slow or buggy interceptor blocks every invocation of that command for the entire IDE. In many cases, listening to events (e.g., document-saved events instead of intercepting the Save command) is less invasive and achieves the same result. Use interception only when you need to run logic before the command executes, or when you need to cancel or replace the default behavior entirely.
When to use this vs. alternatives:
The VisualStudio.Extensibility SDK does not currently support intercepting existing commands. You can only define new commands with Command. There is no equivalent of IOleCommandTarget chaining or VS.Commands.InterceptAsync in the out-of-process model.
If you need to intercept existing commands, use the VSIX Community Toolkit or VSSDK (in-process) approach.
For some scenarios you may be able to achieve similar results by listening to events instead of intercepting the command directly. For example, use IDocumentEventsListener to react to document save events rather than intercepting the Save command.
The Community Toolkit provides VS.Commands.InterceptAsync — a one-line API to intercept any known command by its GUID and ID. You supply callbacks for before and/or after the command executes.
NuGet package: Community.VisualStudio.Toolkit
Key namespace: Community.VisualStudio.Toolkit
using Community.VisualStudio.Toolkit;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
namespace MyExtension;
public sealed class MyExtensionPackage : ToolkitPackage
{
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
await this.RegisterCommandsAsync();
// Intercept the Save command (Ctrl+S)
await VS.Commands.InterceptAsync(VSConstants.VSStd97CmdID.Save, ExecuteBeforeSave, ExecuteAfterSave);
}
private CommandProgression ExecuteBeforeSave()
{
// Return CommandProgression.Continue to let the Save command proceed
// Return CommandProgression.Stop to cancel the Save command
return CommandProgression.Continue;
}
private void ExecuteAfterSave()
{
// Runs after the Save command completes
}
}
CommandProgression.Stopawait VS.Commands.InterceptAsync(VSConstants.VSStd97CmdID.SaveAll, () =>
{
var result = VS.MessageBox.Show(
"Save All",
"Are you sure you want to save all files?",
OLEMSGICON.OLEMSGICON_QUERY,
OLEMSGBUTTON.OLEMSGBUTTON_YESNO);
// Cancel the command if the user clicks No
return result == VSConstants.MessageBoxResult.IDYES
? CommandProgression.Continue
: CommandProgression.Stop;
});
Pass the before-handler only — no after-handler:
await VS.Commands.InterceptAsync(VSConstants.VSStd97CmdID.Build, () =>
{
ThreadHelper.JoinableTaskFactory.Run(async delegate
{
OutputWindowPane pane = await VS.Windows.GetOutputWindowPaneAsync(Windows.VSOutputWindowPane.General);
pane?.WriteLine($"Build started at {DateTime.Now}");
});
return CommandProgression.Continue;
});
Pass null for the before-handler:
await VS.Commands.InterceptAsync(VSConstants.VSStd97CmdID.Build, null, () =>
{
VS.StatusBar.ShowMessageAsync("Build completed!").FireAndForget();
});
Commands are identified by their command group GUID and command ID. The most common are in VSConstants.VSStd97CmdID and VSConstants.VSStd2KCmdID:
| Command | Constant | Description |
|---|---|---|
| Save | VSConstants.VSStd97CmdID.Save | Ctrl+S |
| Save All | VSConstants.VSStd97CmdID.SaveAll | Ctrl+Shift+S |
| Build | VSConstants.VSStd97CmdID.Build | Build Solution |
| Rebuild | VSConstants.VSStd97CmdID.Rebuild | Rebuild Solution |
| Cut | VSConstants.VSStd97CmdID.Cut | Ctrl+X |
| Copy | VSConstants.VSStd97CmdID.Copy | Ctrl+C |
| Paste | VSConstants.VSStd97CmdID.Paste | Ctrl+V |
| Undo | VSConstants.VSStd97CmdID.Undo | Ctrl+Z |
| Redo | VSConstants.VSStd97CmdID.Redo | Ctrl+Y |
| Format Document | VSConstants.VSStd2KCmdID.FORMATDOCUMENT | Format entire document |
| Format Selection | VSConstants.VSStd2KCmdID.FORMATSELECTION | Format selected text |
| Find | VSConstants.VSStd97CmdID.Find | Ctrl+F |
| Replace | VSConstants.VSStd97CmdID.Replace | Ctrl+H |
For commands not in VSConstants, use the overload that takes a CommandID:
using System.ComponentModel.Design;
var commandGuid = new Guid("your-command-group-guid");
var commandId = new CommandID(commandGuid, 0x0100);
await VS.Commands.InterceptAsync(commandId, () =>
{
// Before handler
return CommandProgression.Continue;
});
InterceptAsync must be called after the package is initialized (inside InitializeAsync).CommandProgression.Continue to let the original command execute, or CommandProgression.Stop to cancel it.With the raw VSSDK, command interception is done by implementing IOleCommandTarget and inserting your implementation into the command target chain using IVsRegisterPriorityCommandTarget.
NuGet package: Microsoft.VisualStudio.SDK
Key namespaces: Microsoft.VisualStudio.Shell, Microsoft.VisualStudio.OLE.Interop, Microsoft.VisualStudio.Shell.Interop
IOleCommandTargetusing System;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
namespace MyExtension;
internal sealed class SaveCommandInterceptor : IOleCommandTarget
{
private readonly AsyncPackage _package;
public SaveCommandInterceptor(AsyncPackage package)
{
_package = package;
}
public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
{
// Return OLECMDERR_E_UNKNOWNGROUP to let the next handler in the chain process this
return (int)Constants.OLECMDERR_E_UNKNOWNGROUP;
}
public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
ThreadHelper.ThrowIfNotOnUIThread();
// Check if this is the Save command
if (pguidCmdGroup == typeof(VSConstants.VSStd97CmdID).GUID
&& nCmdID == (uint)VSConstants.VSStd97CmdID.Save)
{
// --- Before logic ---
var result = VsShellUtilities.ShowMessageBox(
_package,
"Save this file?",
"Confirm Save",
OLEMSGICON.OLEMSGICON_QUERY,
OLEMSGBUTTON.OLEMSGBUTTON_YESNO,
OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
if (result != (int)VSConstants.MessageBoxResult.IDYES)
{
// Cancel the command — do not pass it down the chain
return VSConstants.S_OK;
}
}
// Not our command, or we want to continue — let the next handler process it
return (int)Constants.OLECMDERR_E_UNKNOWNGROUP;
}
}
Use IVsRegisterPriorityCommandTarget to insert your IOleCommandTarget at a higher priority than the default handlers:
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[Guid("YOUR-PACKAGE-GUID")]
public sealed class MyExtensionPackage : AsyncPackage
{
private uint _interceptorCookie;
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
var priorityCommandTarget = await GetServiceAsync(typeof(SVsRegisterPriorityCommandTarget))
as IVsRegisterPriorityCommandTarget;
var interceptor = new SaveCommandInterceptor(this);
priorityCommandTarget?.RegisterPriorityCommandTarget(
0, // reserved, must be 0
interceptor,
out _interceptorCookie);
}
protected override void Dispose(bool disposing)
{
if (disposing && _interceptorCookie != 0)
{
ThreadHelper.ThrowIfNotOnUIThread();
var priorityCommandTarget = GetService(typeof(SVsRegisterPriorityCommandTarget))
as IVsRegisterPriorityCommandTarget;
priorityCommandTarget?.UnregisterPriorityCommandTarget(_interceptorCookie);
_interceptorCookie = 0;
}
base.Dispose(disposing);
}
}
IOleCommandTarget.Exec intercepts before the default handler. To run logic after the command executes, you need to let the default handler run first by calling the next target in the chain. The simplest way is to use IVsUIShell.PostExecCommand to queue your post-execution logic, or track state and use IOleCommandTarget chaining.
A simpler approach for after-execution scenarios: use DTE.Events.CommandEvents to listen for command completion:
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.Shell;
// In InitializeAsync, after SwitchToMainThreadAsync:
var dte = await GetServiceAsync(typeof(DTE)) as DTE2;
var commandEvents = dte.Events.CommandEvents;
// Keep a reference to prevent GC
_commandEvents = commandEvents;
commandEvents.AfterExecute += (string guid, int id, object customIn, object customOut) =>
{
// Check if this is the command you care about
if (guid == typeof(VSConstants.VSStd97CmdID).GUID.ToString("B")
&& id == (int)VSConstants.VSStd97CmdID.Save)
{
// Runs after Save completes
}
};
Important: Store a reference to the
CommandEventsobject in a field. If it gets garbage collected, the event handler silently stops firing.
IDocumentEventsListener) as an alternative for some scenarios.VS.Commands.InterceptAsync is the simplest approach. Use CommandProgression.Stop to cancel, CommandProgression.Continue to allow. Call it in InitializeAsync.IOleCommandTarget and register it via IVsRegisterPriorityCommandTarget. Always unregister in Dispose. For after-execution logic, use DTE.Events.CommandEvents.AfterExecute.RunningDocumentTable, IDocumentEventsListener) are more appropriate than command interception.VS.Commands.InterceptAsync is called in InitializeAsync with the correct command GUID and ID. For VSSDK, ensure you called RegisterPriorityCommandTarget and that your IOleCommandTarget.QueryStatus returns OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED.CommandProgression.Stop from your handler to prevent the original command from executing. For VSSDK, return S_OK from Exec without calling the next command target.CommandEvents.AfterExecute, the event fires synchronously after the command returns. If the command's effects are applied asynchronously, your handler may run before they're visible. Use await Task.Yield() or a small delay to let the effects settle.UnregisterPriorityCommandTarget throws: You're calling it from a background thread or after the VS shell has already been disposed. Wrap in ThreadHelper.ThrowIfNotOnUIThread() and check disposal state.Do NOT intercept commands when event listeners suffice — e.g.,
IDocumentEventsListenerfor post-save is less fragile than intercepting Save. Reserve interception for canceling or replacing behavior.
Do NOT do slow work in a before-execution interceptor — it runs synchronously on the UI thread for every invocation.
Do NOT forget to unregister priority command targets in
Dispose— leaked registrations cause crashes on disposed objects.
Do NOT intercept commands in VisualStudio.Extensibility — not supported. Use event listeners (e.g.,
IDocumentEventsListener) instead.
What SKILL.md sets; muted values are Claude Code's defaults
Generated from the plugin's indexed repository (madskristensen/vs-agent-plugins) — no native marketplace selected
npx claudepluginhub p/madskristensen-vs-extensibility-skills41 skills in this plugin
/adding-codelens-indicatorsAdd custom CodeLens indicators that display inline information above code elements in the Visual Studio editor. Use when the user asks how to add a CodeLens indicator, show inline data above methods or classes, create a custom CodeLens provider, implement IAsyncCodeLensDataPointProvider, display git history or test status in CodeLens, or add a details popup to CodeLens entries. Covers VSSDK / VSIX Community Toolkit (in-process + out-of-process CodeLens service). VisualStudio.Extensibility (out-of-process) does not have a dedicated CodeLens API./adding-commandsAdd commands (menu items, toolbar buttons) to Visual Studio extensions. Use when the user asks how to create a command, add a menu item, add a toolbar button, register a command handler, wire up a .vsct file, use KnownMonikers icons on buttons, or place commands in menus/toolbars in a Visual Studio IDE extension. Covers VisualStudio.Extensibility (out-of-process), VSIX Community Toolkit (in-process), and legacy VSSDK (in-process) approaches./adding-context-menusAdd native-looking context menus to custom WPF UI in Visual Studio extensions (tool windows, custom tree views, list views). Use when the user wants to show a right-click context menu from their own UI that looks native to VS. Covers defining VSCT context menus (type="Context"), grouping commands with separators, and programmatically showing them via IVsUIShell.ShowContextMenu. Do NOT use regular WPF ContextMenu — it won't match VS theming or support command routing. Covers VSSDK and VSIX Community Toolkit (in-process). VisualStudio.Extensibility (out-of-process) does not support VSCT-based context menus on custom UI.Other plugins' skills for the same job