I’m having difficulty with the GetForegroundWindow() API function and the .hWnd property.

I want to check whether my application has the focus in the Windows environment and if it does, prevent an automatic time-out. I’m trying to do this by comparing the handle of the window that has the focus in Windows, as returned by GetForegroundWindow(), and the handle of the application’s form, contained in Me.hWnd.

However, it doesn’t work. However, the two handles seem never to equate. I’ve put the relevant code excerpts below.

Can anyone see why it shouldn’t work?

I've noticed that the handle returned by GetForegroundWindow() is always a lot smaller than that of Me.hWnd. For example, GetForegroundWindow() returns 1,238 and Me.hWnd is 591,062.

To avoid complications involving the VB environment, I’m setting the breakpoint for inspection after the two values are captured (in lngHandle1 and lngHandle2.) I’m also running the executable to check whether its working. The application has only one form.

I'm using VB5.



Declare Function GetForegroundWindow Lib "user32" () As Integer

'Form constants
Const TIME_OUT_DURATION = 1.5 'time before time out (mins)

'Form variables
Dim lngTimeOutCount As Long	'counter for time-out timer

Private Sub Form_Load()

 lngTimeOutCount = 0 
 tmrTimeOut.Enabled = False

 'show form

 'start timer
 tmrTimeOut.Enabled = True
End Sub

Private Sub tmrTimeOut_Timer()
 Dim lngHandle1 As Long
 Dim lngHandle2 As Long

 lngTimeOutCount = lngTimeOutCount + 1

 lngHandle1 = GetForegroundWindow()
 lngHandle2 = Me.hWnd
 If lngHandle1 = lngHandle2 Then lngTimeOutCount = 0
 If lngTimeOutCount = Int(60 * TIME_OUT_DURATION) Then End

End Sub

Edited by Ant70: n/a

5 Years
Discussion Span
Last Post by Ant70

No worries...

I've just realised that I declared GetForegroundWindow() as an integer rather than a long. Have corrected the code and it now works.


Edited by Ant70: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.