KeyUp processed for wrong control

Posted by Mikael on Stack Overflow See other posts from Stack Overflow or by Mikael
Published on 2010-03-23T13:40:22Z Indexed on 2010/03/23 13:43 UTC
Read the original article Hit count: 351

Filed under:

I have made a simple test application for the issue, two winforms each containing a button. The button on the first form opens the other form when clicked. It also subscribes to keyup events.

The second form has its button set as "AcceptButton" and in the Clicked event we sleep for 1s and then set DialogResult to true (the sleep is to simulate some processing done)

When enter is used to close this second form the KeyUp event of the button on the first form is triggered, even though the key was released well before the second had passed so the second form was still shown and focused.

If any key other then enter is pressed in the second form the event is not triggered for the button on the first form.

First form:

    public Form1()
    {
        InitializeComponent();
        buttonForm2.KeyUp += new KeyEventHandler(cntKeyUp);
    }

    void cntKeyUp(object sender, KeyEventArgs e)
    {
        MessageBox.Show(e.KeyCode.ToString());
    }

    private void buttonForm2_Click(object sender, EventArgs e)
    {
        using (Form2 f = new Form2())
        {
            f.ShowDialog();
        }
    }

Second form:

    private void button1_Click(object sender, EventArgs e)
    {
        Thread.Sleep(1000);
        this.DialogResult = DialogResult.OK;
    }

Does anyone know why the event is triggered for the button on the non active form and what can be done to stop this from happening?

© Stack Overflow or respective owner

Related posts about c#