Hi,

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.

Thanks.

Ant

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()

 'initialise
 lngTimeOutCount = 0 
 tmrTimeOut.Enabled = False

 'show form
 Me.Show

 '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

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.

Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.