简体   繁体   中英

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?

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 .

Try to put something like this in Timer1_Tick event handler -

Label1.Visible = Not Label1.Visible

Set the timer to enabled and it will do the job.

If you specify the color when the Text is 00:00:05 then you should also specify what the Backcolor should be when the text is something else ie 00:00:06

Try this and see if it works:

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
else
    Label1.Backcolor = Color.Yellow '(Change color as needed)
End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM