2

Is there a simple way to have elements on a form keep updating even after I click on Windows Show Desktop? The following code updates the value in textBox1 until I click on Windows Show Desktop (Windows 10 - click on the bottom right of the screen). I prefer not to use Application.DoEvents().

void Button1Click(object sender, EventArgs e)
{
    int n = 0;
    while(true) {
        textBox1.Text = n++.ToString();
        textBox1.Refresh();
        Update();
        // Application.DoEvents();
        Thread.Sleep(200);
    }
}
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
Nick_F
  • 1,103
  • 2
  • 13
  • 30

1 Answers1

1

Using Thread.Sleep blocks the current thread (UI thread); you can fix it like this:

private async void button1_Click(object sender, EventArgs e)
{
    int n = 0;
    while (true)
    {
        textBox1.Text = n++.ToString();
        await Task.Delay(200);
    }
}
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • Thanks, the code works. If I decide to remove the Task.Delay() alltogether, how can I still have the form updating? – Nick_F Dec 26 '21 at 02:59
  • I don't have a clear idea of why the UI totally freezes right after you click on show desktop; it happens even if you remove the Thread.Sleep. But in the code that I shared, the Task.Delay is giving the UI thread some time to process rest of the messages without blocking UI thread. – Reza Aghaei Dec 26 '21 at 04:38
  • And if you wonder if it's better than Application.DoEvents, the answer is [Yes, of course](https://stackoverflow.com/a/35204137/3110834). – Reza Aghaei Dec 26 '21 at 04:43
  • Thanks Reza. I also prefer to use the Task.Delay() to introduce a tiny delay (and have the UI responsive) rather than using Application.DoEvents(). – Nick_F Dec 26 '21 at 04:48