-->
Get the Active Control of the Foreground Window
Place the code below in a standard module.
|
|
Option Explicit
Private Declare Function GetForegroundWindow Lib "user32" () As Long
Private Declare Function AttachThreadInput Lib "user32" (ByVal idAttach As Long, ByVal idAttachTo As Long, ByVal fAttach As Long) As Long
Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hWnd As Long, lpdwProcessId As Long) As Long
Private Declare Function GetFocus Lib "user32" () As Long
'GetFocus systemwide-----------------------------------------
'returns the hWnd of the Active control of the specified app
'if no hwnd is specified the App in the foreground is checked
Public Function ActiveWindowsControl(Optional hWnd As Long) As Long
'By Arthur Marks, arthurruhtra@netscape.net
'Use at your own risk...
Dim OtherThreadID As Long
If hWnd = 0 Then
'get main window handle - (Screen.ActiveControl.hWnd only good for my app)
hWnd = GetForegroundWindow
End If
'get thread ID of other window
OtherThreadID = GetWindowThreadProcessId(hWnd, ByVal 0)
'For GetFocus to work within another app we must attatch it's thread input
'I'm not sure of the ramifications of this (please tell if you know)
If OtherThreadID <> App.ThreadID Then
'doesn't always work if my thread goes first
If AttachThreadInput(OtherThreadID, App.ThreadID, 1) Then 'attach
'attach was successful
ActiveWindowsControl = GetFocus '(would return zero if foreign window and not attached)
AttachThreadInput App.ThreadID, OtherThreadID, 0 'release
End If
Else
'let's not be narcissistic; dont't attach if same thread
ActiveWindowsControl = GetFocus
End If
End Function