简体   繁体   中英

Why does PostMessage WM_KEYDOWN & WM_KEYUP to textBox produce two characters?

I have a form with a multi-line textBox and a button.

The textBox has a Key Up, Down, and Press event so I can see what happens when you press a key.

When I press the a key while the textBox has focus, it shows:

Down: 65
Press: a
Up: 65

With the button I'm sending a Key Down and Key Up message. With that I get 2 key presses:

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

Please help me understand why this happens.

        [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");
    }

The answer, of course, is that the lParam of the WM_KEYDOWN and WM_KEYUP messages is supposed to contain the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag of the key.

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));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM