views:

389

answers:

1

I have a Windows.Worms application. In one of my forms I display a DataGridView with a ContextMenu (not ContextMenuStrip) associated to it. The MenuItems in the ContextMenu have Shortcuts defined.

This is how the ContextMenu is created:

    Private _contextMenu As _
        New ContextMenu( _
            New MenuItem() { _
                New MenuItem("Item A", AddressOf ItemA_Click, Shortcut.CtrlA) With {.DefaultItem = True}, _
                New MenuItem("Item B", AddressOf ItemB_Click, Shortcut.CtrlB), _
                New MenuItem("Item C", AddressOf ItemC_Click, Shortcut.CtrlC), _
                ...
            }) _
        With {.Name = "MyContextMenu"}

If my DataGridView has the focus and I press Ctrl + A ItemA_Click is called.
Now I want the Shortcut to work for my entire form, even if the DataGridView doesn't have the focus.
The reversed way would be easy, I just have to set KeyPreview of the Form to true. But I want to pass the event down to my DataGridView.

I tried to call the OnKeyDown and OnKeyPress methods from the DataGridView, but both don't seem to work. I don't know it, but I suppose that the ContextMenu ignores the Key... Events and hooks up to the message queue, but I haven't got a clu how to convert my System.Windows.Forms.KeyEventArgs to windows messages.

Just two thinks:
- Focus the DataGridView and use SendKeys as a solution only over my dead body.
- I can't pull the logic out of the ContextMenu and use KeyPreview or smth. like this.

+1  A: 

I think you almost figured it out - try setting the form's KeyPreview to true and then catching the shortcut key yourself. When you catch the shortcut key being pressed, call the appropriate method: (Sorry, this is C# as I'm more familiar with C# syntax...)

private void Form_KeyDown(object sender, KeyEventArgs e) { 
   if (e.Control && e.KeyCode == Keys.A) {
      ItemA_Click(...);
   } else if (e.Control && e.KeyCode == Keys.B) { 
      ItemB_Click(...);
   } else if (e.Control && e.KeyCode == Keys.C) { 
      ItemC_Click(...);
   }
}
Yoopergeek
Hmm...this does have the problem of handling the shortcuts in two seperate places...ie: If you add Ctrl+M to you ContextMenu, you have to remember to handle that in you KeyDown event handler as well. . . Maybe remove the shortcut keys entirely from the ContextMenu so there's only a single point in the code that handles the shortcut keys?
Yoopergeek
@Yoopergeek: That's the point. I cannot move the Shortcuts from the Contextmenu to the Form, because it it dynamically created and the form does not know about it's existance.
SchlaWiener