How to use FindWindow to search for a visible or invisible window with a partial name in VBA

I use the Windows API with Excel VBA to work with a specific window using the FindWindow() function, but FindWindow() requires the full name / signature of the window to search.

Question 1

P_Win = FindWindow(vbNullString, "PlusApi_Excel Sample_17_39_12 Api Generated Orders") in my case the window will change its name (dynamic) (some part of the window name will be fixed, and some part will be dynamic)

Ex. The name of the window for the first time is "PlusApi_Excel Sample_17_39_12 Api Generated Orders" and the second time it will be "PlusApi_Excel Sample_17_45_13 Api Generated Orders" I think I need to call the window with the name of the part, but I don’t know how to do it kindly help me

Question 2

Above the task I have another problem that PlusApi will be hidden, but my code shows a positive value.

It seems to me that I need to call only "visible" .

+6
source share
1 answer

I found the following code in this vbforums.com answer and improved it to look for visible or invisible windows as well, hopefully answering 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 looks for a window with a partial title "Excel" and tells you if it found it, and if it is a visible window or not. You should be able to adapt it for your purposes.

+8
source

Source: https://habr.com/ru/post/973259/


All Articles