Hotkey (not global) in Windows Forms .NET

不问归期 提交于 2019-11-27 03:18:51

问题


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?


回答1:


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



回答2:


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;
    }
}



回答3:


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



来源:https://stackoverflow.com/questions/2790913/hotkey-not-global-in-windows-forms-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!