0

I'm doing a prototype c# program to test out a concept I have. The prototype is a simple for loop (10x) that sets a textbox background color property to a randomly generated color and then waits 2 seconds and does it again.

        for (int i = 0; i < 10; i++)
        {
            Color NewColor = GetRandomColor();
            tbLight1.BackColor = NewColor;
            Application.DoEvents();

            WaitNSeconds(2);
        }

Using the debug feature I know that the random color generator works and the code does a loop through 10 times. However, I only see the final color in the text box. I have tried Refresh(), Update(), Invalidate(), and now Application.DoEvents. They all result in the same. I only see the final color, not the 9 before it. I don't know what else to try.

Here is the WaitNSeconds() method. This I got from stackoverflow. I'm going to use Thread.Sleep(2000); instead.

    private void WaitNSeconds(int segundos)
    {
        if (segundos < 1) return;
        DateTime _desired = DateTime.Now.AddSeconds(segundos);
        while (DateTime.Now < _desired)
        {
            System.Windows.Forms.Application.DoEvents();
        }
    }

Note: Since this has been flagged as a duplicate, I have moved to that question to proceed. Thanks!

John Slate
  • 29
  • 1
  • 7
  • 1
    What are you doing in WaitNSeconds? Just use a WinForms Timer. – LarsTech Sep 19 '17 at 16:15
  • I have tried the "Application.DoEvents();" It does not work either in this situation. I am working on the BackgroundWoker approach but that seems like a lot of work just to change the textbox background color. This is a prototype. Once I get this working I want to have a 3x3 display of 9 textboxes, each independently and randomly changing the background color, for a random amount of time (1 - 5 seconds). – John Slate Sep 20 '17 at 15:16
  • The method "WaitNSeconds" I found on stackoveflow. – John Slate Sep 20 '17 at 15:17
  • private void WaitNSeconds(int segundos) { if (segundos < 1) return; DateTime _desired = DateTime.Now.AddSeconds(segundos); while (DateTime.Now < _desired) { System.Windows.Forms.Application.DoEvents(); } } – John Slate Sep 20 '17 at 15:18
  • It's not clear to me why you just don't use a timer? In the tick event, change your color. You should probably stay away from DoEvents. See [Use of Application.DoEvents()](https://stackoverflow.com/q/5181777/719186). For what it's worth, your code worked for me. My textbox kept changing colors. – LarsTech Sep 20 '17 at 15:25
  • Thanks LarsTech. Okay, so I use the tick event to drive the process. I'll give it a try. I think that approach is cleaner.... – John Slate Sep 20 '17 at 16:51

0 Answers0