Do something today meet to add a shortcut key to the button. Here are three ways to add shortcut keys.
First ALT + * (Button shortcut key)
When you set the Text property for a button, label, MenuStrip, and so on, add the & key name after the name, for example button1.text= "OK (&a)". There will be shortcut keys, press Alt+a to execute the button click event.
The second type of ctrl+* and other key combinations
In WinForm, set the KeyPreview (Register keyboard event to form) property of the form to use the key combination, and then use the form's KeyDown event (which occurs when a key is first pressed).
Instance code:
Private void form name _keydown (object sender, KeyEventArgs e)
{
if (E.keycode = = keys.f && e.control)
{
Button1. PerformClick (); //Perform the action of clicking Button1
}
}
Note: You can take a look at the "Keys" enumeration parameters to achieve your own needs
When you use the CTRL + * Shortcut key, the * key value may be entered at the same time for the focus on a writable control, such as a TextBox, and you need to add another word to set handled to trueto cancel the KeyPress event
The following code:
Private void ***_keydown (object sender, KeyEventArgs e)
{
if (E.keycode = = keys.f && e.control)
{
e.handled = true; //Set handled to true to indicate that the KeyPress event has been processed
Button1. PerformClick ();
}
}
KeyDown event response for the third form add shortcut key
Private void form name _keydown (object sender, KeyEventArgs e)
{
if (E.keycode = = Keys.enter)
{
Button_Click (sender, E);
}
}
C # WinForm Add a shortcut key response to a button or other control