Search code examples
ms-accessvbams-access-2007

Forms GotFocus event does not seem to fire


I'm trying to call an event when the user returns focus to the Access application when a specific form is open. The following event doesn't seem to fire up at all.

Private Sub Form_GotFocus()
    Call crtListDirectory
End Sub 

Does any body have any ideas as to how I could trigger this event to happen, and when/how does the Form_GotFocus event actually get triggered.

thanks in advance for any help

Noel


Solution

  • Access help:

    A form can get the focus only if all visible controls on a form are disabled, or there are no controls on the form.

    You might like to try Activate.

    EDIT re Comments

    The only way I can see of doing what you seem to want is with APIs, which is somewhat messy. To demonstrate this you will need a form with two controls Text0 and Text2 (these are the default names). Set the Timer Interval to something suitable, say 2000, and the Timer Event to:

    Private Sub Form_Timer()
    Dim lngWin As Long
    Dim s As String
    
        'This is just a counter to show that the code is running
        Me.Text2 = Nz(Me.Text2, 0) + 1
    
        'API
        lngWin = GetActiveWindow()
        s = GetWinName(lngWin)
    
        If s = "Microsoft Access" Then
            If Me.Text0 = "Lost Focus" Then
                Me.Text0 = "Focus returned"
            End If
        Else
            Me.Text0 = "Lost Focus"
        End If
    
    End Sub
    

    You will now need a module for:

    Option Compare Database
    
    Declare Function GetActiveWindow Lib "user32" () As Integer
    Declare Function GetWindowText Lib "user32.dll" Alias _
    "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As _
    String, ByVal cch As Long) As Long
    Declare Function GetWindowTextLength Lib "user32" Alias _
    "GetWindowTextLengthA" (ByVal hwnd As Long) As Long
    
    Function GetWinName(hw As Long)
        Dim lngText As Long ' receives length of text of title bar
        Dim strWinName As String ' receives the text of the title bar
        Dim lngWinText As Long ' receives the length of the returned string
    
        lngText = GetWindowTextLength(hw)
        strWinName = Space(lngText + 1)
        lngWinText = GetWindowText(hw, strWinName, lngText + 1)
        strWinName = Left(strWinName, lngWinText)
        GetWinName = strWinName
    End Function
    

    This is all very, very rough, but it gives you something to mess about with.