views:

151

answers:

3

In my winform app 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 app i can press the key and it will fire off my event?

+1  A: 

If you have just one form. You can set the Form.KeyPreview=true and then add code to the form's key event.

eschneider
+3  A: 

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;
    }
}
Hans Passant
ProcessCmdKey FTW
acidzombie24
I had this one marked accept but then i saw zach write `return base.ProcessCmdKey(ref msg, keyData);` and i felt like an idiot (i use to do that but i iddnt this time) and updated my code. He gets it for having his answer remind me of my mistake. Although you had more answers. It was a hard choice.
acidzombie24
+4  A: 

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);
}
Zach Johnson