How to properly set the shortcut key of ToolStripButton in VB .NET? Specially, there is the WebBrowser control in the form. And some important notes about this.

Posted by Admin L in .NET Programming on 26-03-2013. Tags: , , , , , , , , , , ,

Author: Nosa Lee
Original Address:
To reprint this article, please indicate the source, thank you.

In .NET, the ToolStripButton control does not support shortcut key, that is, it has not ShortcutKeys property, so, you need to code for it to get this ability.

There are two common ways, one is implement it in Form’s KeyDown/KeyUp events (need to set Form.KeyPreview as True), another is through ToolStripMenuItem control, because this control supports shortcut key (has ShortcutKeys property).

Through practice, I found using ToolStripMenuItem to implement the shortcut key of ToolStripButton is the best method, if your program does not need menus, just hide the MenuStrip control.

1. When the focus on some special controls (e.g. WebBrowser), it cannot respond Form’s KeyDown/KeyUp events.
2. Calling the function of ToolStripButton in ToolStripMenuItem is easier than determining the pressed keys and then calling the ToolStripButton function in Form’s KeyDown/KeyUp, and can get the more concise code.
Among them, the first is the main reason.

1. Create the corresponding ToolStripMenuItems for the ToolStripButtons that need shortcut keys.
2. Set the shortcut keys of ToolStripMenuItems as you need.
3. Call the ToolStripButton function in ToolStripMenuItem’s Click event or the parent ToolStripMenuItem’s DropDownItemClicked event.

Special Notes
If there is WebBrowser control in the form, please note that try not to allocate the WebBrowser’s built-in shortcut keys (e.g. <Ctrl+O> Open command) to the ToolStripMenuItem if you implemented the ToolStripButton’s shortcut key through above way.

Reason: if the focus in WebBrowser, then pressing the WB’s built-in shortcut keys may call the corresponding function of WebBrowser first, and does not respond ToolStripMenuItem Click/DropDownItemClicked events.
1. Some built-in shortcut keys can be used for ToolStripMenuItem, such as <F5> Refresh command, some will conflict, e.g. <Ctrl+O> Open command. So, you need to test them first, and then assign the proper keys to ToolStripMenuItems.
2. If you still want to use the conflict keys (e.g. <Ctrl+O> Open), I suggest you add <Alt> key directly (e.g. <Ctrl+Alt+O>) to compromise to maximum retain user’s habit.
3. At first glance, setting WebBrowser.WebBrowserShortcutsEnabled property as False can avoid the conflicts, but in fact it does not work. If you did this, then when the focus in WB control, it cannot respond the ToolStripMenuItem’s shortcut key and the Form’s KeyDown/KeyUp events.

Other Note
Above experiences are not only for .NET platform, should also apply to VB6, Delphi and other programming languages.

【赞赏 / Reward】

微信         支付宝         PayPal

Post a comment