Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 302
  • Last Modified:

Check control focus and change backcolor

Hello Experts,

I was wondering if there is a easy way of doing this.

I would like to change the BackColor of the control on a windows Form that has the focus. When the control has the Focus, I would like the BackColor to be say Yellow; when the control looses focus I would like the BackColor to go back to White.

I know I could use the GotFocus event of each control but If I have 20 controls on a form that would not be a good pratice to do like that.

Thanks for your sugestions.

jppinto
0
jppinto
Asked:
jppinto
1 Solution
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Try something like this...
Public Class Form1
 
    Private PrevBackColor As Color
 
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        WireControls(Me)
    End Sub
 
    Private Sub WireControls(ByVal cont As Control)
        For Each ctl As Control In cont.Controls
            Try
                AddHandler ctl.GotFocus, AddressOf ctl_GotFocus
                AddHandler ctl.LostFocus, AddressOf ctl_LostFocus
            Catch ex As Exception
            End Try
            If ctl.HasChildren Then
                WireControls(ctl)
            End If
        Next
    End Sub
 
    Private Sub ctl_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim ctl As Control = CType(sender, Control)
        PrevBackColor = ctl.BackColor
        ctl.BackColor = Color.Yellow
    End Sub
 
    Private Sub ctl_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim ctl As Control = CType(sender, Control)
        ctl.BackColor = PrevBackColor
    End Sub
 
End Class

Open in new window

0
 
jppintoAuthor Commented:
Hello Idle_Mind,

Your solution is perfect (as always!). Thanks,

jppinto
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now