Form WM_KEYDOWN and WM_KEYUP messages aren't captured in WndProc

爷,独闯天下 提交于 2019-12-19 04:35:43

问题


Form keydown and keyup messages aren't captured:

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

    protected override void WndProc(ref Message m)
    {
        if (m.Msg == WM_KEYDOWN)
        {
            log("down");
        }
        if (m.Msg == WM_KEYUP)
        {
            log("up");
        }
        base.WndProc(ref m);
    }
}

回答1:


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("<CTRL> + M Captured");
                    break;

                case Keys.Alt | Keys.Z:
                    Debug.WriteLine("<ALT> + 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



来源:https://stackoverflow.com/questions/20408071/form-wm-keydown-and-wm-keyup-messages-arent-captured-in-wndproc

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