Form WM_KEYDOWN and WM_KEYUP messages aren't captured in WndProc

前端 未结 1 1919
难免孤独
难免孤独 2021-01-07 05:19

Form keydown and keyup messages aren\'t captured:

public partial class Form1 : Form
{
    const int WM_KEYDOWN = 0x100;
    const int WM_KEYUP = 0x101;

             


        
1条回答
  •  有刺的猬
    2021-01-07 05:28

    You should override ProcessCmdKey instead

    This example is extracted from this article

    public partial class Form1 : Form, IMessageFilter
    {
        const int WM_KEYDOWN = 0x100;
        const int WM_KEYUP = 0x101;
        const int WM_SYSKEYDOWN = 0x104;
        Keys lastKeyPressed = Keys.None;
        public Form1()
        {
            InitializeComponent();
            Application.AddMessageFilter(this);
            this.FormClosed += (s, e) => Application.RemoveMessageFilter(this);
        }
        public bool PreFilterMessage(ref Message m) 
        {
            if(m.Msg == WM_KEYUP)
            {
                Debug.WriteLine("Filter -> KeyUp LastKeyPressed=" + lastKeyPressed.ToString());
            }
            return false;
        }
    
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if ((msg.Msg == WM_KEYDOWN) || (msg.Msg == WM_SYSKEYDOWN))
            {
                lastKeyPressed = keyData;
                switch (keyData)
                {
                    case Keys.Down:
                        Debug.WriteLine("Down Arrow Captured");
                        break;
    
                    case Keys.Up:
                        Debug.WriteLine("Up Arrow Captured");
                        break;
    
                    case Keys.Tab:
                        Debug.WriteLine("Tab Key Captured");
                        break;
    
                    case Keys.Control | Keys.M:
                        Debug.WriteLine(" + M Captured");
                        break;
    
                    case Keys.Alt | Keys.Z:
                        Debug.WriteLine(" + Z Captured");
                        break;
                }
            }
    
            return base.ProcessCmdKey(ref msg, keyData);
        }
                
    

    Probably there is a way to extract the KeyCode from the message passed to the PreFilterMessage as explained in this article

    0 讨论(0)
提交回复
热议问题