View Single Post
  #8   Report Post  
Posted to microsoft.public.excel.programming
RB Smissaert RB Smissaert is offline
external usenet poster
 
Posts: 2,452
Default APIs FindWindow and GetWindowText

As it worked and speed never was an issue I never looked if it could
be improved, but will have a look now and thanks in case it can.

RBS


wrote in message
oups.com...
On Sep 9, "RB Smissaert" wrote:
This code should do the job:
.. Function FindWindowHwndLike( ..


I don't know what you guys get for "moderating" this group, but I
recommend you get a raise.
This function is EXACTLY what I want. I spent quite a bit of time on
it and in so doing took out
(what I think to be) unneeded recursion variables and LIKE syntax.
So I humbly present my improved version. It seems to work the same as
yours.
But let me thank you again for a VERY enlightening post. D-C

Option Explicit

Private Declare Function GetDesktopWindow& Lib "user32" ()
Private Declare Function GetWindow& Lib "user32" ( _
ByVal hWnd As Long, _
ByVal wCmd As Long)
Private Declare Function GetWindowText& Lib "user32" _
Alias "GetWindowTextA" ( _
ByVal hWnd As Long, _
ByVal lpString As String, _
ByVal cch As Long)
Private Declare Function GetClassName& Lib "user32" _
Alias "GetClassNameA" ( _
ByVal hWnd As Long, _
ByVal lpClassName As String, _
ByVal nMaxCount As Long)
Private Const GW_HWNDNEXT = 2
Private Const GW_CHILD = 5

Dim zTraceRow&

Sub Test1()
zTraceRow = 0
ActiveSheet.Cells.Clear
MsgBox LoopFindWindow(0, "XLMAIN", "Microsoft Excel")
End Sub

Function LoopFindWindow(hWndStart&, ClassName$, WindowTitle$)
' based on FindWindowHwndLike by RB Smissaert
Dim hWndV&, hWndCh&, sWindowTitle$, sClassName$, r%
hWndV = hWndStart
' 1st time is 0
If hWndV = 0 Then hWndV = GetDesktopWindow()
Do While hWndV 0 ' loop thru siblings
' Get the window text
sWindowTitle = Space$(255)
r = GetWindowText(hWndV, sWindowTitle, 255)
sWindowTitle = Left$(sWindowTitle, r)
' get the class name
sClassName = Space$(255)
r = GetClassName(hWndV, sClassName, 255)
sClassName = Left$(sClassName, r)
If 1 Then zTrace hWndV, sClassName, sWindowTitle
' if satisfactory, then done
If sWindowTitle Like WindowTitle & "*" And _
sClassName Like ClassName & "*" Then
LoopFindWindow = hWndV
Exit Function
End If
' check for child window
hWndCh = GetWindow(hWndV, GW_CHILD)
' if yes, use recursion
If hWndCh < 0 Then hWndCh = LoopFindWindow(hWndCh, ClassName,
WindowTitle)
' if a hit, then done
If hWndCh < 0 Then
LoopFindWindow = hWndCh
Exit Function
End If
' next sibling
hWndV = GetWindow(hWndV, GW_HWNDNEXT)
Loop
LoopFindWindow = 0 ' no hit
End Function

Sub zTrace(hWnd&, sC$, sT$)
zTraceRow = zTraceRow + 1
Cells(zTraceRow, 1) = hWnd
Cells(zTraceRow, 2) = sC
Cells(zTraceRow, 3) = sT
DoEvents
End Sub