Hotkey (not global) in Windows Forms .NET

大憨熊 提交于 2019-11-28 09:58:53

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.

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