如何使用vba中的windowapi中的findwindow函数找到窗口? [英] How to locate the window using findwindow function in windowapi using vba?
问题描述
我正在尝试找到一种方法来检查窗口是否使用Findwindow函数打开。如果我知道窗口的整个名称,我可以找到窗口。在下面的代码中,我知道窗口的名称是win32api - 记事本,所以我可以很容易地找到窗口,但是我想知道是否可以识别窗口,如果我只知道部分名称,如win32 *。
I am currently trying to find a way to check whether a window is open or not using Findwindow Function. I am able to find the window if i know the entire name of the window. In the below code i know that the name of the window is "win32api - Notepad" so i can easily find the window however i want to know whether it is possible to identify the window if i know only part name like "win32*".
Public Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Sub runapplication()
hwnd = FindWindow(vbNullString, "win32api - Notepad")
MsgBox (hwnd)
End Sub
推荐答案
您可以通过 EnumWindows API函数。由于它通过回调函数进行操作,因此您需要将标准和结果缓存在超出调用函数范围的某个位置:
One way you can do this is with the EnumWindows API function. Since it operates via a callback function, you'll need to cache both the criteria and the results somewhere that has scope beyond the calling function:
Public Declare Function EnumWindows Lib "user32" (ByVal lpEnumFunc As Long, _
ByVal param As Long) As Long
Public Declare Function IsWindowVisible Lib "User32" (ByVal hWnd As Long) As Long
Public Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" _
(ByVal hwnd As Long, _
ByVal lpString As String, _
ByVal cch As Long) As Long
Public Const MAX_LEN = 260
Public results As Dictionary
Public criteria As String
Public Sub Example()
criteria = "win32*"
Set results = New Dictionary
Call EnumWindows(AddressOf EnumWindowCallback, &H0)
Dim result As Variant
For Each result In results.Keys
Debug.Print result & " - " & results(result)
Next result
End Sub
Public Function EnumWindowCallback(ByVal hwnd As Long, ByVal param As Long) As Long
Dim retValue As Long
Dim buffer As String
If IsWindowVisible(hwnd) Then
buffer = Space$(MAX_LEN)
retValue = GetWindowText(hwnd, buffer, Len(buffer))
If retValue Then
If buffer Like criteria Then
results.Add hwnd, Left$(buffer, retValue)
End If
End If
End If
EnumWindowCallback = 1
End Function
这篇关于如何使用vba中的windowapi中的findwindow函数找到窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!