0

This code changes bg color only once. What do I need to add to get it working?

 int i=0;
        while (i<50)
        {
            button1.BackColor = Color.White;
            Thread.Sleep(20);
            button1.BackColor = Color.Black;
            Thread.Sleep(20);
            i++;
        }
Dr_Freeman
  • 261
  • 1
  • 5
  • 12
  • sleep 20 is almost equivalent to 0. maybe you only *see* one color change? What are you trying to accomplish, there's probably a better way to do what you're trying to do. – John Gardner Apr 03 '12 at 15:51
  • 1
    See http://stackoverflow.com/q/952906/ – H H Apr 03 '12 at 15:52
  • But Sleep()ing on the main thread for 50*40 ms is not a good idea. – H H Apr 03 '12 at 15:53
  • I have changed sleep to 1000, doesn't work either. I need to simulate something. I'm trying to code symbols by using only two states black-white. Then I'll use photosensitive diode to get information to my mC. – Dr_Freeman Apr 03 '12 at 15:55
  • @JasminPvvlovic Please let us know the big picture ,what you are trying to accomplish ? – DayTimeCoder Apr 03 '12 at 15:57

1 Answers1

2

Even if you change the sleep argument to something bigger, if you are operating on the same thread where form is operating (main thread), you will not see any change because you are blocking the main thread; instead you should either use another thread or just use the Timer component of windows forms.

    int i;
    public Form1()
    {
        InitializeComponent();            
        System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
        timer.Interval = 200;
        timer.Tick += new EventHandler(timer_Tick);
        this.BackColor = Color.White;
        timer.Start();
    }

    void timer_Tick(object sender, EventArgs e)
    {
        if (this.BackColor == Color.White)
            this.BackColor = Color.Black;
        else
            this.BackColor = Color.White;
    }
daryal
  • 14,643
  • 4
  • 38
  • 54