Change background colour of a control on gotfocus

dhj

New member
Joined
Jul 15, 2004
Messages
1
Programming Experience
1-3
hi
i need to change the background colour of a control (say textbox for a example) when it has gotfocus and change back to the original colour when lostfocus. (in a vb.net windows application)



i know i can write subs for each and every control as follows


Private Sub TextBox1_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.LostFocus

End Sub



Private Sub TextBox1_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus

End Sub
 
Hi, you can create events in a form that is inherited by all of your forms. That way the event will be associated with each control, on every form. So if you like, create a form, put no controls on it (because the controls will be inherited also) and throw this code into it.
Private Sub SetEventHandlers(ByVal ctrlContainer As Control)
If UCase(ctrlContainer.Text) = "FRMTURBO" Then Exit Sub
Dim ctrl As Control
For Each ctrl In ctrlContainer.Controls
If TypeOf ctrl Is TextBox Then
AddHandler ctrl.Enter, AddressOf ProcessEnter
AddHandler ctrl.Leave, AddressOf ProcessLeave
AddHandler ctrl.DoubleClick, AddressOf ProcessClick
ElseIf TypeOf ctrl Is DataGrid Then
AddHandler ctrl.BindingContextChanged, AddressOf ProcessBindingContextChanged
End If
If ctrl.HasChildren Then
SetEventHandlers(ctrl)
End If
Next
End Sub

Private Sub ProcessEnter(ByVal sender As Object, ByVal e As System.EventArgs)
If Me.blEventExit Then Exit Sub
If blBlue = False Then Exit Sub
DirectCast(sender, TextBox).BackColor = Color.Wheat
End Sub

Private Sub ProcessLeave(ByVal sender As Object, ByVal e As System.EventArgs)
If Me.blEventExit Then Exit Sub
If blBlue = False Then Exit Sub
DirectCast(sender, TextBox).BackColor = System.Drawing.Color.FromArgb(CType(214, System.Byte), CType(223, System.Byte), CType(245, System.Byte))
End Sub

Private Sub ProcessClick(ByVal sender As Object, ByVal e As System.EventArgs)
If Me.blEventExit Then Exit Sub
If blBlue = False Then Exit Sub
DirectCast(sender, TextBox).BackColor = Color.Wheat
End Sub

Private Sub ProcessBindingContextChanged(ByVal sender As Object, ByVal e As System.EventArgs)
DirectCast(sender, DataGrid).AlternatingBackColor = System.Drawing.Color.FromArgb(CType(214, System.Byte), CType(223, System.Byte), CType(245, System.Byte))
DirectCast(sender, DataGrid).BackColor = Color.WhiteSmoke
End Sub

I got this code from DevX, I would have just sent you a link, but I could not find the article anymore.
-Edward
 
Back
Top