Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 Other Forums
 MS Access
 Using GotFocus and LostFocus Events

Author  Topic 

sqlslick
Yak Posting Veteran

83 Posts

Posted - 2011-07-14 : 16:01:32
Hello all,

I am trying to use the GotFocus and LostFocus events to change the back colour a control that gets or loses the focus. Here is the code:

Private Sub AnyControl_GotFocus()
AnyControl.BackColor = RGB(190, 236, 245)
End Sub

Private Sub cboService_LostFocus()
AnyControl.BackColor = RGB(255, 255, 255)
End Sub

The GotFocus event works great but the LostFocus doesn't seem to work. The back colour of the object reamins the same as when the object GotFocus. I have googled the issue and there appears to be issues with the LostFocus event not being too reliable.

I was able to find code that calls a Public procedure from the Form_Open event and sets the back colour of the object that has focus accordingly, but it does not work when I set focus to a control that is on a subform. Here is the code:

Function GotFocus()

On Error GoTo HandleError

Screen.ActiveControl.BackColor = RGB(190, 236, 245)

EndOfSub:
Exit Function

HandleError:
If Err = 438 Then
Resume Next
Else
Err.Raise Err
Resume EndOfSub
End If

End Function

Function LostFocus()

On Error GoTo HandleError

Screen.ActiveControl.BackColor = RGB(255, 255, 255)

EndOfSub:
Exit Function

HandleError:
If Err = 438 Then
Resume Next
Else
Err.Raise Err
Resume EndOfSub
End If

End Function

Sub FocusChanges(ByVal frm As Form)

On Error GoTo HandleError

Dim ctl As Control

For Each ctl In frm
ctl.OnGotFocus = "=GotFocus()"
ctl.OnLostFocus = "=LostFocus()"
Next

EndOfSub:
Exit Sub

HandleError:
If Err = 438 Then
Resume Next
Else
Err.Raise Err
Resume EndOfSub
End If

End Sub

Any suggestions will be greatly appreciated.

Thank you!!
John

sqlslick
Yak Posting Veteran

83 Posts

Posted - 2011-07-15 : 10:08:15
I've been able to simplify the code using the following:

Public Sub HasFocus(ctl As Control)
On Error Resume Next
ctl.BackColor = RGB(190, 236, 245)
End Sub

Public Sub LoseFocus(ctl As Control)
On Error Resume Next
ctl.BackColor = RGB(255, 255, 255)
End Sub

Then I call each procedure from each control's GotFocus() and LostFocus() events. This seems to work great too. However, when I set focus to a control in a subform the GotFocus() event seems to work but AGAIN not the LostFocus(). The control changes to colour as expected but when it loses focus it remains the same, it does not change.

Anybody?
Go to Top of Page
   

- Advertisement -