There's another way to do this in WinForms without your having to override 'ProcessCommandKey, set Form 'KeyPreView to 'true, etc.; It's a little "hackish," but I hope it will round-out the discussions here.
1. Put a MenuStrip on the Form: if you don't want to use the MenuStrip to show some Menu Items, set its 'Visible Property to 'false.
2. Add a ToolStripMenuItem to the MenuStrip in the usual way. Set its ShortCutKeys to the key combination you want to trigger an event. Set its 'Visible Property to 'false.
3. Add a Click EventHandler to the ToolStripMenuItem, and write the code you wish executed when the Click happens.
Example:
I add a MenuStrip, 'menuStrip11. I add a ToolStripMenuItem, 'AltF4ShortCut with the key-combination set to 'Alt and 'F4. In the Designer view of the Form, you'll see:
this.AltF4ShortCut.Name = "AltF4ShortCut";
this.AltF4ShortCut.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.F4)));
this.AltF4ShortCut.Size = new System.Drawing.Size(52, 24);
this.AltF4ShortCut.Text = "Save";
this.AltF4ShortCut.Visible = false;
this.AltF4ShortCut.Click += new System.EventHandler(this.AltF4ShortCut_Click);
Now, the Click EventHandler will fire no matter what Control has focus in the run-time Form; I could have the current focus set to a TextBox in a Panel in a UserControl, and it will still fire.
Here's what the Click EventHandler might look like:
private void AltF4ShortCut_Click(object sender, EventArgs e)
{
if (MessageBox.Show(
"Save now ?",
"Save Data",
MessageBoxButtons.OKCancel,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button1,
MessageBoxOptions.DefaultDesktopOnly
)
== DialogResult.OK)
{
}
}
I think it's safe to assume that a WinForm app with menu item with shortcut key-combinations defined installs its own lower-lever handler for Keyboard events, perhaps even using whatever the ProcessCmdKey over-ride uses under-the-hood (maybe WndProc ?).