You can invoke most commands with a keyboard shortcut in addition to a menu entry or button on a command bar. You can set these keyboard shortcuts on a per-command basis by using the Command.Bindings
property. This property returns or accepts a SafeArray
(essentially an array of objects) that contains each shortcut as an element of the array.
Key bindings are represented as strings with the following format: [scopename]::[modifier+][key]
.
Scopename
is used to refer to the scope where the shortcut is valid, such as Text Editor
or Global
. The modifier
token is used to specify the key modifier, such as Ctrl+, Alt+, or Shift+. (Modifiers are not required.) And the key
is the keyboard key that is pressed (in conjunction with the modifier if present) to invoke the command.
To add a binding to an existing command, you need to retrieve the current array of binding values, add your binding string to the array, and then assign the whole array back into the Bindings
property like this.
Commands2 commands As = (Commands2)_applicationObject.Commands;
Command cmd =
commands.Item("File.SaveSelectedItems");
object[] bindings;
bindings = cmd.Bindings;
// Increase the array size by 1 to hold the new binding
Array.Resize<object>(ref bindings, bindings.GetUpperBound(0) + 1);
// Assign the new binding into the array
bindings(bindings.GetUpperBound(0)) = "Global::Shift+F2";
// Assign the array back to the command object
cmd.Bindings = bindings;
Note
You can create your own named commands that can be launched from a command bar in the IDE (or from the command window for that matter). The Command
object itself is added to the Commands
collection by calling Commands.AddNamedCommand
. The code that runs when the command is executed has to be implemented by an add-in. We cover this scenario in Chapter 15.