ToolStripButton does not have a ShortcutKeys property the way a ToolStripMenuItem does. If you want a function key or any other keyboard shortcut to trigger a toolbar button, you need to intercept the keystroke at the form level yourself.
The most common scenario is a toolbar with an Execute or Refresh button that users expect to trigger with F5, matching the behaviour they know from Visual Studio, SQL Server Management Studio, and similar tools.
Override ProcessCmdKey on the form and call PerformClick on the target ToolStripButton when the matching key is pressed. ProcessCmdKey intercepts keystrokes before any focused control gets a chance to handle them, which makes it the right place for form-wide shortcuts.
' Assigning Shortcut Keys to ToolStrip Buttons
Protected Overrides Function ProcessCmdKey(
ByRef msg As System.Windows.Forms.Message,
ByVal keyData As System.Windows.Forms.Keys) As Boolean
Select Case keyData
Case Keys.F5
ExecuteToolStripButton.PerformClick()
Case Else
'Do Nothing
End Select
Return MyBase.ProcessCmdKey(msg, keyData)
End Function
Returning MyBase.ProcessCmdKey(msg, keyData) at the end is important. It passes any unhandled keys back up the chain so that standard shortcuts such as Ctrl+C, Ctrl+Z, and arrow key navigation continue to work normally throughout the form.
Case Keys.F5 Or Keys.Control. The keyData parameter includes modifier flags, so this comparison works exactly as expected.
The Select Case block scales cleanly to as many shortcuts as you need. Add one Case per key combination and call PerformClick on the corresponding button:
Protected Overrides Function ProcessCmdKey(
ByRef msg As System.Windows.Forms.Message,
ByVal keyData As System.Windows.Forms.Keys) As Boolean
Select Case keyData
Case Keys.F5
ExecuteToolStripButton.PerformClick()
Case Keys.F5 Or Keys.Control
CancelToolStripButton.PerformClick()
Case Keys.F2
EditToolStripButton.PerformClick()
Case Else
'Do Nothing
End Select
Return MyBase.ProcessCmdKey(msg, keyData)
End Function
- Any form with a
ToolStripwhere users expect keyboard shortcuts to match familiar tools such as SSMS, Visual Studio, or Excel. - Data entry forms where a single Execute or Save button needs to be reachable from the keyboard without the user moving their hands to the mouse.
- Situations where adding a
ToolStripMenuItemwith aShortcutKeysproperty is not appropriate because the menu item itself should not be visible to users.
No comments: