LAamanni LAamanni - 6 months ago 19
Vb.net Question

How to blink an object in VB.NET

I have many controls in my form, like pictureboxes, buttons and textboxes. I made a timer that will blink a control when I ask.

How do I pass the control as a reference, so I could choose easily, which control to blink?

I tried to make a class, "BlinkingObject.vb", to where I pass the control and colors as properties, but I can't make this a reference of the original object...
The idea was, that my timer picks the control from BlinkingObject.vb -class and then changes its backcolor...

I want to have custom colors (upcolor and downcolor) and the control's original background will be needed also.

Answer

This code blinks the control, and doesn't hog the UI thread

' you need the delegate because there is no Action(of byref)
Private Delegate Sub blinkDel(ByRef myControl As Control, ByVal c As Color)

' the Sub you call to blink the control
Public Shared Sub Blink(ByRef myControl As Control, ByVal c As Color)
    ' call performBlink asynchronously as not to take up time on the UI thread
    CType(AddressOf performBlink, blinkDel).BeginInvoke(myControl, c, Nothing, Nothing)
End Sub

' performs the blinking actions
Private Shared Sub performBlink(ByRef myControl As Control, ByVal blinkColor As Color)
    ' invoke the action of setting the backcolor on the UI thread
    myControl.Invoke(New blinkDel(AddressOf setBackColor), myControl, blinkColor)
    ' sleep this thread for how long it should blink
    Thread.Sleep(100)
    ' restore the back color on the UI thread
    myControl.Invoke(New blinkDel(AddressOf setBackColor), myControl, Color.White)
End Sub

' need a named sub because you can't have a ByRef in a lambda (otherwise would be inside performBlink)
Private Shared Sub setBackColor(ByRef myControl As Control, ByVal c As Color)
    myControl.BackColor = c
End Sub

' calling it inside a timer
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Blink(TextBox1, Color.Black)
End Sub