A basic C# Problem.
I have two disabled textboxes on my form, and one button. The button is currently like so:
private void start_Click(object sender, EventArgs e)
{
this.two();
this.hold();
this.one()
}
As you can see it calls three other methods that are like so:
- “two” – Makes both the text boxes BackColor, black.
- “one” – Makes just one of the boxes BackColor Black.
- “hold”
- Calls “System.Threading.Thread.Sleep(1000);” to pause the program for a second.
- Changes the backcolour for both the text boxes back to white.
The problem I am encountering is that program seems to skip the first call to two. And just hold the program for a second and change one textbox to black.
Thanks for any help!
What you are probably experiencing is that you are running this code on the application’s main thread, which is also responsible for responding to Windows GUI messages (like the command to repaint itself after you have changed the textboxes’ colors). The program currently does not process this message until after this event handler has completely executed, at which time only one textbox is black.
Application.DoEvents(), as mentioned, will solve the problem by interrupting this handler and allowing the program to process the queued messages from the GUI before proceeding. Another way to do this would be to run this code in a BackgroundWorker, which would use a separate processing thread to tell the GUI thread to recolor the textboxes, while not blocking the GUI thread with the Sleep() command. Generally, using a multithreaded approach is better, as Application.DoEvents() can cause unexpected consequences by forcing the invocation of other event handlers while the current one hasn’t finished (for instance, a call to another event handler that throws an exception will throw out through the Application.DoEvents call of the one you’ve interrupted, which didn’t actually have a problem).