I am using the Windows API with Excel VBA to work with a particular window, using the FindWindow()
function, but FindWindow()
requires the full title/caption of the window to find.
Question 1
P_Win = FindWindow(vbNullString, "PlusApi_Excel Sample_17_39_12 Api Generated Orders")
in my case the window will change the name (dynamic) (some part of the window name will be fixed and some part will be dynamic)
Ex. The window name is first time "PlusApi_Excel Sample_17_39_12 Api Generated Orders"
and second time it will be "PlusApi_Excel Sample_17_45_13 Api Generated Orders"
I think I need to call window with part name but I don’t know how to do with kindly help me
Question 2
Above challenge I have one more problem the PlusApi will be hidden but my code shows still a positive value.
I think I need to call "visible"
window only.
I found the following code in this vbforums.com answer and enhanced it to look for visible or invisible windows as well, therefore hopefully answering both your questions:
Option Explicit
Private Declare Function FindWindow Lib "User32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) 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 Declare Function GetWindowTextLength Lib "User32" Alias "GetWindowTextLengthA" (ByVal hWnd As Long) As Long
Private Declare Function GetWindow Lib "User32" (ByVal hWnd As Long, ByVal wCmd As Long) As Long
Private Declare Function IsWindowVisible Lib "User32" (ByVal hWnd As Long) As Boolean
Private Const GW_HWNDNEXT = 2
Private Sub Test()
Dim lhWndP As Long
If GetHandleFromPartialCaption(lhWndP, "Excel") = True Then
If IsWindowVisible(lhWndP) = True Then
MsgBox "Found VISIBLE Window Handle: " & lhWndP, vbOKOnly + vbInformation
Else
MsgBox "Found INVISIBLE Window Handle: " & lhWndP, vbOKOnly + vbInformation
End If
Else
MsgBox "Window 'Excel' not found!", vbOKOnly + vbExclamation
End If
End Sub
Private Function GetHandleFromPartialCaption(ByRef lWnd As Long, ByVal sCaption As String) As Boolean
Dim lhWndP As Long
Dim sStr As String
GetHandleFromPartialCaption = False
lhWndP = FindWindow(vbNullString, vbNullString) 'PARENT WINDOW
Do While lhWndP <> 0
sStr = String(GetWindowTextLength(lhWndP) + 1, Chr$(0))
GetWindowText lhWndP, sStr, Len(sStr)
sStr = Left$(sStr, Len(sStr) - 1)
If InStr(1, sStr, sCaption) > 0 Then
GetHandleFromPartialCaption = True
lWnd = lhWndP
Exit Do
End If
lhWndP = GetWindow(lhWndP, GW_HWNDNEXT)
Loop
End Function
The code searches for a window with a partial title of "Excel" and tells you if it found it and if it's a visible window or not. You should be able to adapt it for your own purposes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With