5

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.

Kirsten
  • 15,730
  • 41
  • 179
  • 318

3 Answers3

12

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);
}
Mike Fuchs
  • 12,081
  • 6
  • 58
  • 71
2

Did you try adding "&" symbol in front of the button caption?

Text = "&Save"

Ankit Goel
  • 353
  • 1
  • 4
  • 13
0

You can override the AddStandardItems method and overload the ToolStripMenuItem's constructor to accept ToolStripItem as a parameter for easier creation of the items.

But it's still sort of "replacing the items one by one".

Matus
  • 410
  • 5
  • 15
  • Is there a way to override AddStandardItems and still retain the way the position text works? At the moment I cant see how overriding is any better than simply not calling AddStandardItems - and adding the buttons one by one. In overriding AddStandardItems, I need to know how to hook the buttons up to the events, where to get the icons from, and how to make the record number text work the same way – Kirsten Mar 03 '13 at 19:03
  • it probably is not any better, it's just reusable – Matus Mar 03 '13 at 21:19