Shortcut keys are commonly used functions of many software. This article explains three methods to implement C# button shortcut keys, such as Alt + * (button shortcut key), Ctrl + * and other key combinations. The details are now as follows:
1. The first type of C# button shortcut key: Alt + * (button shortcut key)
When you set Text properties for button, label, menuStrip and other controls, just add the & key name after the name, such as = "&O". There will be a shortcut key. At this time, press Alt+O to execute the button click event.
2. The second type of C# button shortcut key: Ctrl+* and other combination keys
Set the KeyPreview (Register keyboard events with form) property in WinForm to use key combinations to True;
Then use the KeyDown event of the form (occurred when a key is first pressed).
The C# button shortcut key instance code is as follows:
private void ***_KeyDown(object sender, KeyEventArgs e) { if ( == && ) { (); //Execute the action of clicking button1} }
Note here:
1. *** represents the form name. You can take a look at the enumeration parameters of "Keys" to realize your needs.
2. There is another problem. When using the Ctrl + * shortcut key, when the focus is on a writable control (such as TextBox), the * key value may be entered at the same time. You need to add another sentence to set Handled to true to cancel the KeyPress event.
Right now:
private void ***_KeyDown(object sender, KeyEventArgs e) { if ( == && ) { = true; //Set Handled to true to indicate that the KeyPress event has been processed (); } }
3. The third method of C# button shortcut key
Let’s take button as an example. Add a contextMenuStrip1 to form and bond it to button, assuming it is button1. Add an item to contextMenuStrip1, then set a shortcut key for it (that is the shortcut key you want to add to the button), and set its Visible property to false. In this way, the C# button shortcut key is set successfully.
4. The fourth method of C# button shortcut key
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (keyData == ()) { (); } return (ref msg, keyData); }
I hope that the methods described in this article can help you learn from and help others in C# programming.