65.9K
CodeProject is changing. Read more.
Home

Implementing shortcut keys for toolstrip

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.50/5 (2 votes)

Aug 21, 2011

CPOL
viewsIcon

37992

How to activate a toolstrip button via a shortcut key

The first time I used the toolstrip, I was surprised by the fact that toolstrip buttons don't have a shortcut key attribute. Luckily there is a simple workaround. First, create the button handlers for the toolstrip. E.g.
    private void btnOk_Click(object sender, EventArgs e) {
      Accept = true;
      Close();
    }

    private void btnCancel_Click(object sender, EventArgs e) {
      Close();
    }
Next, implement the KeyDown event handler for the form. In the following example, Ctrl+Enter is used to activate the OK button and Escape to activate the Cancel button.
private void RenameF_KeyDown(object sender, KeyEventArgs e) {
  if (e.Control == true && e.KeyValue == 13) {
    btnOk_Click(sender,null);
  }
  if (e.KeyValue == 27) {
     btnCancel_Click(sender, null);
  }
}
Finally, you must set the form's KeyPreview attribute to true. This has to be done in order to have the keyPress event from the child controls passed to the form's handler.
private void MainF_Load(object sender, EventArgs e) {
  this.KeyPreview = true;
}
That's it!