Using the SuppressKeyPress event to block a KeyUp event

In the KeyDown event, I used SuppressKeyPressto avoid calls KeyPressand KeyUp. However, although the event KeyPresswas stopped, the event KeyUpstill fires. Why is this?

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.H)
    {
        listBox1.Items.Add("key down" + e.KeyCode);
        // e.SuppressKeyPress = true;
    }
}

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == 'h')
    {
        listBox1.Items.Add("key press" + e.KeyChar);
    }
}

private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
    if(e.KeyCode==Keys.H)
    {
        listBox1.Items.Add("key up" + e.KeyCode);
    }
}
0
source share
2 answers

Taking a look at how SuppressHeyPress is handled in the Control class:

protected virtual bool ProcessKeyEventArgs(ref Message m)
{
    // ...
    if (e.SuppressKeyPress)
    {
        this.RemovePendingMessages(0x102, 0x102);
        this.RemovePendingMessages(0x106, 0x106);
        this.RemovePendingMessages(0x286, 0x286);
    }
    return e.Handled;
}

Obviously, you cannot do something like this to suppress the WM_KEYUP message (when you process the KeyDown event, the KeyPress message is already sent to your control, but the KeyUp message does not fire until the user releases the key).

You can verify this with the following code:

[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool PeekMessage([In, Out] ref MSG msg, HandleRef hwnd, int msgMin, int msgMax, int remove);

[Serializable, StructLayout(LayoutKind.Sequential)]
public struct MSG
{
    public IntPtr hwnd;
    public int message;
    public IntPtr wParam;
    public IntPtr lParam;
    public int time;
    public int pt_x;
    public int pt_y;
}

private void RemovePendingMessages(Control c, int msgMin, int msgMax)
{
    if (!this.IsDisposed)
    {
        MSG msg = new MSG();
        IntPtr handle = c.Handle;
        while (PeekMessage(ref msg, new HandleRef(c, handle), msgMin, msgMax, 1))
        {
        }
    }
}

private void SuppressKeyPress(Control c)
{
    this.RemovePendingMessages(c, 0x102, 0x102);
    this.RemovePendingMessages(c, 0x106, 0x106);
    this.RemovePendingMessages(c, 0x286, 0x286);
}

private void SuppressKeyUp(Control c)
{
    this.RemovePendingMessages(c, 0x101, 0x101);
    this.RemovePendingMessages(c, 0x105, 0x105);
}

private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.H)
    {
        SuppressKeyPress(sender);       // will work
        SuppressKeyUp(sender);          // won't work
    }
}

suppressKeyUp, true KeyDown KeyUp, , , (, ).

+1

,

e.Handled = true;

e.Suppress... = true;.

0

Source: https://habr.com/ru/post/1537730/


All Articles