0

Hi I have been trying to add a button into my program that when you click the button it displays text in a label, waits so the user can read it, then exits the program. but if I run it and try it it only waits then exits without displaying text. sorry if that was a bad explanation I just got into coding. This is what I have.

private void button3_Click(object sender, EventArgs e)
{
    label1.Text = "Text Here";
    Thread.Sleep(500);
    this.Close();
}
Ron Beyer
  • 11,003
  • 1
  • 19
  • 37

2 Answers2

3

Call label1.Invalidate() to force the control to be redrawn. When you call Thread.Sleep, the UI thread will be blocked and not update.

If this doesn't work, try label1.Refresh() or Application.DoEvents();

private void button3_Click(object sender, EventArgs e)
{
    label1.Text = "Text Here";
    label1.Invalidate();
    Thread.Sleep(500);
    this.Close();
}

A more ideal solution would be to use a timer, another thread, or some kind of async event to run the code separately from your UI:

timer = new Timer();
timer.Interval = 500;
timer.Tick += (sender, e) => Close();
timer.Start();

or

new Thread(delegate() { 
    Thread.Sleep(500);
    this.Close(); 
}).Start();

Also note that 500 milliseconds is a pretty short time, did you mean 5000 milliseconds, which is equivalent to 5 seconds? You may want to also take a look at Winforms: Application.Exit vs Enviroment.Exit vs Form.Close, as Close() closes the current window.

Community
  • 1
  • 1
Cyral
  • 13,999
  • 6
  • 50
  • 90
1

Instead of using Thread.Sleep which blocks the UI thread (and keeps it from updating with your text), its better to keep the UI responsive. This will keep the UI working and delay then close the application.

private void button3_Click(object sender, EventArgs e)
{
    label1.Text = "Text Here";
    Task.Delay(5000).ContinueWith((arg) => Application.Exit());
}

The Task is run in another thread, delays for the specified milliseconds (5000 or 5 seconds in this case) then continues with a call to close the application.

By the way, this.Close() works to close the application only if the form you are running it from is the "initial" form of the application. If you ran the same code from another child form, it would only close the form. The better thing to do if you want to actually close the application is to use the Application.Close() method. This gracefully closes the application. If you want to down-right terminate, you can use Environment.Exit(int).

Ron Beyer
  • 11,003
  • 1
  • 19
  • 37