C # WinForm Add a shortcut key response to a button or other control

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.