Mar 202011
 

Let’s take small project as an example. You need two or three options and you cram everything as root menu item. Since you like your users and your users like pictures, you additionally create toolbar with same options. Final toolbar has one-to-one mapping with menu. Now question is why do we need menu in first place?

Personally I see only one reason – keyboard accessibility. Toolbar might be nice but it will not allow us to use pure keyboard interface in order to select items. However, solution is simple. First we set KeyPreview=true on form itself and then we just handle Alt key:

private void MainForm_KeyDown(object sender, KeyEventArgs e) {
    switch (e.KeyData) {
        case Keys.Alt | Keys.Menu: {
            menu.Select();
            menuNew.Select();
            e.SuppressKeyPress = true;
            e.Handled = true;
        } break;
    }
}

This code acts upon Alt key press. First we need to select ToolStrip control and then we select first item (New, in this case) within it. If we just use Select on item it will look same, but keyboard arrows will not move selection between items.

Downside to this is handling shortcut keys. While MenuItem will allow us to set Ctrl+N as shortcut key same is not true for ToolStripButton. All shortcuts should be handled explicitly now (within MainForm_KeyDown event):

···
case Keys.Control | Keys.N:
    menuNew_Click(null, null);
    e.SuppressKeyPress = true;
    e.Handled = true;
    break;
···

Full code example is available here.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>