ProcessCmdKey - wait for KeyUp?

前端 未结 2 2065
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-18 07:59

I\'m having the following issue in a WinForms app. I\'m trying to implement Hotkeys and I need to process Key messages whenever the control is active, no matter if the focus

相关标签:
2条回答
  • 2020-12-18 08:41

    I thought it'd be easy, just look at the key's repeat count. Didn't work though if modifiers are used. You'll need to see the key go up as well, that requires implementing IMessageFilter. This worked:

    public partial class Form1 : Form, IMessageFilter {
        public Form1()  {
            InitializeComponent();
            Application.AddMessageFilter(this);
            this.FormClosed += (s, e) => Application.RemoveMessageFilter(this);
        }
        bool mRepeating;
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
            if (keyData == (Keys.Control | Keys.F) && !mRepeating) {
                mRepeating = true;
                Console.WriteLine("What the Ctrl+F?");
                return true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }
        public bool PreFilterMessage(ref Message m) {
            if (m.Msg == 0x101) mRepeating = false;
            return false;
        }
    }
    
    0 讨论(0)
  • 2020-12-18 08:44
    const int WM_KEYDOWN = 0x100;
    const int WM_KEYUP = 0x101;
    
    protected override bool ProcessKeyPreview(ref Message m)
    {
        if (m.Msg == WM_KEYDOWN && (Keys)m.WParam == Keys.NumPad6)
        {
            //Do something
        }
        else if (m.Msg == WM_KEYUP && (Keys)m.WParam == Keys.NumPad6)
        {
            //Do something
        }
    
        return base.ProcessKeyPreview(ref m);
    }
    
    0 讨论(0)
提交回复
热议问题