John the great
John the great

Reputation: 11

Show and Hide a label in windows forms continuously

I want to show and hide a label continuously (using sleep in a for loop). Here is what I am doing:

for (i = 0; i < 25; i++)
{
      label1.Visible = true;
      Thread.Sleep(1000);
      label1.Visible = false;
      Thread.Sleep(2000);
}

However, the above code is not working as expected. I don't see the label at all. Any idea how to achieve this

Upvotes: 0

Views: 244

Answers (1)

Rolando Corratge Nieves
Rolando Corratge Nieves

Reputation: 1233

Using Thread.Sleep freezes the Windows of youre interface you must run a separated tread or use a Timer that do it for you Example:

    void blinkLabel()
    {
        int blink_times = 25;

        System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();            

        timer1.Interval = 1000;//every one second

        timer1.Tick += new System.EventHandler((s, e) =>
        {
            if (blink_times >= 0)
            {
                label1.Visible = !label1.Visible;
                blink_times--;
            }
            else
            {
                timer1.Stop();
            }
        }
        );


        timer1.Start();
    }   

Upvotes: 1

Related Questions