Indentifying when my application gets focus

Hello Experts,

     I need a way to determine when my application has recieved focus, either through clicking on the application in the taskbar or by clicking on the form window.  The form_GotFocus and _LoseFocus do not achieve this goal, since form_GotFocus only fires when all of the other applicable controls are disabled.  Is there a way, via API or not, to be able to do this?  I need to be able to open a file and input the contents when the application gets focus and in the interest of efficiency for the end-user, I would prefer them not to have to make an additional click.

Any and all help is greatly appreciated, this is a last-minute design change for a deadline project.

gwosgoodIT MgrAsked:
Who is Participating?
iHadiConnect With a Mentor Commented:
Hi gwosgood
The following code demonstrates a simple and affective way of gaining your goal without complicated subclassing. Add a timer and a command buton to a form, st the timer interval to 100 and paste the following code:

Private Declare Function GetForegroundWindow Lib "user32" () As Long
Dim PrevActive As Boolean

Private Sub Form_GotFocus()
    MsgBox "Activated"
End Sub

Private Sub Timer1_Timer()
Dim WinHandle As Long

WinHandle = GetForegroundWindow

If Me.hWnd = WinHandle Then
    If PrevActive = False Then
        PrevActive = True
    End If
    PrevActive = False
End If
End Sub
Mike TomlinsonMiddle School Assistant TeacherCommented:
You need to subclass and then trap the WM_ACTIVATE msg as in this PAQ:
gwosgoodIT MgrAuthor Commented:
Thank you very much iHadi, a very simple solution, just the thing I was looking for.

One quick question though, what was the purpose of the command button?
You got me! I was writing another post that used a command button and it looks like you got a copy of my thoughts too. In this solution you do not need it only if you like clicking on empty coded buttons!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.