1

How can I add a shortcut to a certain button in windows forms application?

For an instance I want to assign the combination CTRL+R to my exit button, so when I press it, the code in that particular button executes.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • 2
    Look here http://stackoverflow.com/questions/400113/best-way-to-implement-keyboard-shortcuts-in-a-windows-forms-application – Plue Jan 30 '14 at 13:22

1 Answers1

6

Write an ampersand ("&") in the Text property of the button before a character to have Alt+that key as the shortcut.

E.g.:

myButton.Text = "Press &me";

would make Alt+M the shortcut.

Beware of duplicates and ensure you only assign a shortcut once per form. You can also assign shortcuts to e.g. Label control to make the control next to the label (in the tab order) get the focus, e.g. a text box control.

If you want to have Ctrl instead of Alt take a look at this SO question, as Plue commented. Be aware that Alt+some key is the usual way, so better have a good reason to change the default behavior.

Community
  • 1
  • 1
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • and if i want to make it ctrl + m? –  Jan 30 '14 at 13:27
  • Then, take a look at [this SO question](http://stackoverflow.com/questions/400113/best-way-to-implement-keyboard-shortcuts-in-a-windows-forms-application), as [Plue commented](http://stackoverflow.com/questions/21457687/adding-a-shortcut-to-a-button-in-windows-forms-ap/21457747#comment32380519_21457687). Be aware that `Alt`+`some key` is the usual way, so better have a good reason to change the default behavior. – Uwe Keim Jan 30 '14 at 13:28
  • 1
    Wrong link for **this SO question** – Plue Jan 30 '14 at 13:30