为什么PostMessage WM_KEYDOWN& WM_KEYUP到textBox产生两个字符?

时间:2018-03-23 22:09:41

标签: c#

我有一个带有多行textBox和一个按钮的表单。

textBox有一个Key Up,Down和Press事件,所以我可以看到按键时会发生什么。

当textBox具有焦点时按a键,它会显示:

Down: 65
Press: a
Up: 65

使用按钮我正在发送Key DownKey Up消息。有了这个,我得到了两次按键:

Down : 65
Up : 65
Press : a
Press : a

请帮助我理解为什么会这样。

        [DllImport("user32.dll")]
    static extern bool PostMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);

    const uint WM_KEYDOWN = 0x0100;
    const uint WM_KEYUP = 0x0101;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        PostMessage(textBox1.Handle, WM_KEYDOWN, 65, 0);
        PostMessage(textBox1.Handle, WM_KEYUP, 65, 0);
    }

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        textBox1.AppendText("Down : " + e.KeyValue.ToString() + "\r\n");
    }

    private void textBox1_KeyUp(object sender, KeyEventArgs e)
    {
        textBox1.AppendText("Up : " + e.KeyValue.ToString() + "\r\n");
    }

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        textBox1.AppendText("Press : " + e.KeyChar.ToString() + "\r\n");
    }

1 个答案:

答案 0 :(得分:0)

当然,答案是WM_KEYDOWN和WM_KEYUP消息的lParam应该包含重复计数,扫描代码,扩展密钥标志,上下文代码,先前的密钥状态标志和过渡状态标志。关键。

private void button1_Click(object sender, EventArgs e)
    {
        uint repeatCount = 0;
        uint scanCode = 0;
        uint extended = 0;
        uint context = 0;
        uint previousState = 0;
        uint transition = 0;

        uint lParamDown;
        uint lParamUp;

        scanCode = 65;
        lParamDown = repeatCount
            | (scanCode << 16)
            | (extended << 24)
            | (context << 29)
            | (previousState << 30)
            | (transition << 31);
        previousState = 1;
        transition = 1;
        lParamUp = repeatCount
            | (scanCode << 16)
            | (extended << 24)
            | (context << 29)
            | (previousState << 30)
            | (transition << 31);
        PostMessage(textBox1.Handle, WM_KEYDOWN, (UIntPtr)65, unchecked((IntPtr)(int)lParamDown));
        PostMessage(textBox1.Handle, WM_KEYUP, (UIntPtr)65, unchecked((IntPtr)(int)lParamUp));
    }