In my Windows Forms application I would like one special button to run a test everytime I press it. There are dozens of controls so implementing it in each one takes too much time.
Is there a way I can set a hotkey so, no matter what I am doing in the application, I can press the key, and it will fire off my event?
You can override ProcessCmdKey
and handle your hotkeys there, either in a control or a form.
From MSDN:
The ProcessCmdKey method first
determines whether the control has a
ContextMenu, and if so, enables the
ContextMenu to process the command
key. If the command key is not a menu
shortcut and the control has a parent,
the key is passed to the parent's
ProcessCmdKey method. The net effect
is that command keys are "bubbled" up
the control hierarchy. In addition to
the key the user pressed, the key data
also indicates which, if any, modifier
keys were pressed at the same time as
the key. Modifier keys include the
SHIFT, CTRL, and ALT keys.
For example:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
// if it is a hotkey, return true; otherwise, return false
switch (keyData)
{
case Keys.Control | Keys.C:
// do something
return true;
default:
break;
}
return base.ProcessCmdKey(ref msg, keyData);
}
You can override a form's ProcessCmdKey() method, it runs before any control on the form will see the key stroke. If you really need this to be at the application level (all forms) then you should have your main form implement the IMessageFilter interface. For example:
public partial class Form1 : Form, IMessageFilter {
public Form1() {
InitializeComponent();
Application.AddMessageFilter(this);
this.FormClosed += (o, e) => Application.RemoveMessageFilter(this);
}
public bool PreFilterMessage(ref Message m) {
// Catch WM_KEYDOWN message
if (m.Msg == 0x100 && (Keys)m.WParam == Keys.F1) {
MessageBox.Show("Help me!");
return true;
}
return false;
}
}
If you have just one form. You can set the Form.KeyPreview=true and then add code to the form's key event.