Option Explicit
' Module Name: ModFindWindowLike
' (c) 2005 Wayne Phillips (
http://www.everythingaccess.com)
' Written 02/06/2005
#If VBA7 Then
Private Declare PtrSafe Function EnumWindows Lib "user32" _
(ByVal lpEnumFunc As LongPtr, _
ByVal lParam As LongPtr) As LongPtr
Private Declare PtrSafe Function GetWindowText Lib "user32" _
Alias "GetWindowTextA" _
(ByVal hWnd As LongPtr, _
ByVal lpString As String, _
ByVal cch As LongPtr) As Long
Private Type FindWindowParameters
strTitle As String 'INPUT
hWnd As LongPtr 'OUTPUT
End Type
#Else
Private Declare Function EnumWindows Lib "user32" _
(ByVal lpEnumFunc As Long, _
ByVal lParam As Long) As Long
Private Declare Function GetWindowText Lib "user32" _
Alias "GetWindowTextA" _
(ByVal hWnd As Long, _
ByVal lpString As String, _
ByVal cch As Long) As Long
Private Type FindWindowParameters
strTitle As String 'INPUT
hWnd As Long 'OUTPUT
End Type
#End If
'Custom structure for passing in the parameters in/out of the hook enumeration function
'Could use global variables instead, but this is nicer.
Public Function FnFindWindowLike(strWindowTitle As String) As Long
'We'll pass a custom structure in as the parameter to store our result...
Dim Parameters As FindWindowParameters
Parameters.strTitle = strWindowTitle ' Input parameter
Call EnumWindows(AddressOf EnumWindowProc, VarPtr(Parameters))
FnFindWindowLike = Parameters.hWnd
End Function
Private Function EnumWindowProc(ByVal hWnd As Long, _
lParam As FindWindowParameters) As Long
Dim strWindowTitle As String
strWindowTitle = Space(260)
Call GetWindowText(hWnd, strWindowTitle, 260)
strWindowTitle = TrimNull(strWindowTitle) ' Remove extra null terminator
If strWindowTitle Like lParam.strTitle Then
lParam.hWnd = hWnd 'Store the result for later.
EnumWindowProc = 0 'This will stop enumerating more windows
Else
EnumWindowProc = 1
End If
End Function
Private Function TrimNull(strNullTerminatedString As String)
Dim lngPos As Long
'Remove unnecessary null terminator
lngPos = InStr(strNullTerminatedString, Chr$(0))
If lngPos Then
TrimNull = Left$(strNullTerminatedString, lngPos - 1)
Else
TrimNull = strNullTerminatedString
End If
End Function