Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a label blink

I have a Stopwatch in my form with Interval = 1000 displayed in the hh:mm:ss format.

When it reaches the 5th second it should start to blink the label background as green but so far I can only make the background color turn to green without any flash.

This is how I turn the background color to green:

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Label1.Text = SW.Elapsed.ToString("hh\:mm\:ss")
    If Label1.Text = "00:00:05" Then
        Label1.BackColor = Color.Green
    End If
End Sub

How do I make the label blink?

like image 857
Eaten Taik Avatar asked Jan 04 '23 07:01

Eaten Taik


1 Answers

You could use a simple Async method to do this.

The following code will give Label1 the effect of flashing. Since we have used While True this will continue indefinitely once you hit "00:00:05".

Private Async Sub Flash()
    While True
        Await Task.Delay(100)
        Label1.Visible = Not Label1.Visible
    End While
End Sub

You would call this inside your Timer1_Tick method:

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Label1.Text = SW.Elapsed.ToString("hh\:mm\:ss")
    If Label1.Text = "00:00:05" Then
        Label1.BackColor = Color.Green
        Flash()
    End If
End Sub

If you only want to flash a couple of times we can make a simple change to Flash():

Private Async Sub Flash()
    For i = 0 To 10
        Await Task.Delay(100)
        Label1.Visible = Not Label1.Visible
    Next

    'set .Visible to True just to be sure
    Label1.Visible = True
End Sub

By changing the number 10 to a number of your choice you can shorten or lengthen the time taken to flash. I have added in Label1.Visible = True after the For loop just to be sure that we see the Label once the flashing has finished.

You will have to import System.Threading.Tasks to make use of Task.Delay.

like image 152
Bugs Avatar answered Jan 08 '23 13:01

Bugs