Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I assign shortcut keys to buttons on the bindingNavigator?

Is there a way to assign shortcut keys to the standard navigation ToolStrip Items in a BindingNavigator?

The items that get added using the .AddStandardItems method are of type ToolStripItem which doesn't have a ShortcutKeys property.

I tried to cast to ToolStripMenuItem , but it fails.

 public void ConfigureMyNavigator()
    {
               // Adds ToolStripItems which don't support shortcut keys           
                m_navigator.AddStandardItems();

                // Adds a ToolStripMenuItem which can support a shortcut key
                var button = new ToolStripMenuItem
                {
                    Size = new Size(0, 0),
                    Text = "Save",
                    ShortcutKeys = (Keys)Shortcut.CtrlS,
                    ToolTipText = "Press Ctrl+S to save"
                };
                button.Click += tsmi_Click;

                m_navigator.Items.Add(button);

                //   This fails with invalid cast exception
                ((ToolStripMenuItem)m_navigator.Items[1]).ShortcutKeys = (Keys)Shortcut.AltLeftArrow;


    }

I guess I could replace the toolstripitems with toolstripmenuitems one by one, but feel this is rather awkward.

like image 624
Kirsten Avatar asked Feb 28 '13 03:02

Kirsten


1 Answers

You can listen for key commands and then raise the click of the appropriate ToolStripButton. Override the ProcessCmdKey method in your form code:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    switch (keyData)
    {
        case (Keys.Alt | Keys.Left):
            m_navigator.Items[1].PerformClick();
            break;
        case (Keys.Alt | Keys.Right):
            m_navigator.Items[6].PerformClick();
            break;
    }

    return base.ProcessCmdKey(ref msg, keyData);
}
like image 152
Mike Fuchs Avatar answered Nov 03 '22 01:11

Mike Fuchs