Application.DoEvents eating messages?

G

Guest

Background:

I am helping someone debug a problem with their form that I have traced to a
strange interaction between a click event handler and Application.DoEvents().
I'm trying to talk him into using mutithreading.

Problem in its essence:

create a simple Form with 2 buttons and a label. button1 starts a
long-running counting process, button 2 stops the counting process. The
first click of the mouse after the button 1 click gets lost. The second and
subsequent clicks work fine.

What's going on?

code snippet (C# .NET 2.0)

bool cancel = false;
int count = 0;

private void button1_Click(object sender, EventArgs e)
{
cancel = false;
while (cancel == false)
{
label1.Text = count.ToString();
Application.DoEvents();
count ++;
}

}

private void button2_Click(object sender, EventArgs e)
{
cancel = true;
}

Thanks
 
G

Guest

Why not using timer?

int count = 0;

private void button1_Click(object sender, System.EventArgs e)
{
timer1.Enabled = true;
}

private void button2_Click(object sender, System.EventArgs e)
{
timer1.Enabled = false;
}

private void timer1_Tick(object sender, System.EventArgs e)
{
label1.Text = count.ToString();
count ++;
}

You made a loop inside the button1_click event so the event haven't
completed. You can see whatever you click on the form, the focus is still
kept in button1. Therefore, your second click is treated as button1_click
but focus changed to your new control. Then the consequence click works
fines. I don't know whether it is bug or normal behavior. Anyway, looping
for events is not a good programming style.
 
G

Guest

Tedmond said:
Why not using timer?

Thanks for your response.

I agree that looping for events is not good programming style.

A timer works well for this simple example. In the real program, the button
click starts a lon-running process that can't be broken up into discrete
steps the way that incrementing a variable can. I believe the right choice
in this particular case is running a worker thread.

Be that as it may, there still seems to be a bug or at least undocumented
weirdness in calling Application.DoEvents() from a Click event handler. If
the handler does not call DoEvents() the second click is delivered correctly
(after the handler finishes running). If it does call DoEvents() the second
click never arrives anywhere. Third and subsequent clicks all work correctly.

If this is normal behavior, then the Application.DoEvents() examples that
I've seen also have problems.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top