Dynamic hotkeys for Visual Studio extension
-
21-04-2021 - |
Question
Is there any way I can dynamically add global hotkeys from within a Visual Studio extension / package?
Declaring the hotkeys in the *.vsct file of my package is no option because I do not know which hotkeys should be available at runtime - there is kind of a plugin-system within my extension that can add/remove hotkeys dynamically.
Adding a message filter does only work when .NET runs the message loop - which is not the case in VS.
Thanks for your support!
Solution
The best way to add hot keys is to go ahead and define your commands without any key bindings. Essentially make sure that the command MyExtension.MyOperation
is available but bound to no keys.
At run time you can grab the DTE.Command
object for your extension command. It's available through the Commands
property on the DTE
object. From there you can change the key the particular command is bound to by setting the Binding
property.
For example if you wanted to change the binding to CTRL+o I would do the following
command.Binding = "Global::ctrl+o";
The syntax for the key binding is actually fairly well documented on MSDN.