0

I need to change the background color of the current control to make it easier for users to see where they are on complex forms. I'm calling the following Sub from both the GotFocus and LostFocus events to turn background color on and off, and when turning on, I want to select all text in the control. Background color changes are working perfectly, but SelectAll doesn't work. Here's the Sub:

    Public Sub P_Focus(ByRef sender As Object, ByVal Focus As Boolean)
    Static Dim lBackColor As Color
    Select Case True
        Case TypeOf sender Is TextBox
            Dim obj As TextBox = DirectCast(sender, TextBox)
            If Focus = True Then
                lBackColor = obj.BackColor
                obj.BackColor = Color.FromArgb(255, 255, 192)
                obj.SelectAll()
            Else
                obj.BackColor = lBackColor
            End If
    End Select
End Sub

I eliminated all but the TextBox case for brevity.

Can anyone help?

Peter Kipe
  • 87
  • 8
  • 2
    Make sure the `TextBox` is the `ActiveControl` before calling `SelectAll()`. Call `obj.Select()` or `obj.Focus()` just before `obj.SelectAll()`. –  Jan 25 '20 at 07:45
  • 1
    .Select did it. Thanks! – Peter Kipe Jan 25 '20 at 08:25
  • 1
    I would suggest that you instead use the Enter and Leave events instead, see: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.gotfocus?view=netframework-4.8 – Kate Jan 25 '20 at 23:00
  • 1
    Thanks Anonymous - code is changed. Get/LostFocus is a 20+ year old habit. For the record, my original code was working when tabbing into a field, but I had been testing by clicking into the field, and that was not working. I resolved the problem by adding a MouseUp event that fires a similar subroutine I called P_Select, and that does only a SelectAll. Also note that there is no SelectAll event on a NumericUpDown control; the event is .Select(start, length) which I coded as .Select(0, obj.Text.Length). Intellisense doesn't recognize Text, but it's there... – Peter Kipe Jan 26 '20 at 05:28

0 Answers0