开发者

KeyUp processed for wrong control

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" an开发者_开发百科d 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?


You're making a blocking call, then closing the form, before the WM_KEYUP message is sent.

By the time the message is sent, the second form is gone, so currently focused control is on the first form.

You can solve this by calling BeginInvoke in the second form's click handler to only hide the form in the next message loop (after the KeyUp)


One way around:

You can verify in cntKeyUp if the sender is the Form that you expect then you process it, otherwise ignore.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜