使用User32.INSTANCE.FindWindow获取的窗体不准确,如果有相同的名称的应用,我该如何精准获取
时间: 2024-05-04 07:21:23 浏览: 130
如果有多个相同名称的窗体,可以通过获取窗体的类名或者父窗体来精确获取。可以使用User32.INSTANCE.FindWindowEx来获取子窗体,或者使用User32.INSTANCE.EnumWindows来枚举所有窗体,然后根据窗体的属性来判断是否是目标窗体。具体实现可以参考以下代码:
```java
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinUser;
public class WindowUtils {
/**
* 查找指定名称和类名的窗体
*
* @param className 窗体类名
* @param windowName 窗体名称
* @return 窗体句柄
*/
public static WinDef.HWND findWindow(String className, String windowName) {
return User32.INSTANCE.FindWindow(className, windowName);
}
/**
* 查找指定父窗体下指定类名和名称的子窗体
*
* @param parent 父窗体句柄
* @param className 子窗体类名
* @param windowName 子窗体名称
* @return 子窗体句柄
*/
public static WinDef.HWND findWindowEx(WinDef.HWND parent, String className, String windowName) {
return User32.INSTANCE.FindWindowEx(parent, null, className, windowName);
}
/**
* 枚举所有窗体,查找指定类名和名称的窗体
*
* @param className 窗体类名
* @param windowName 窗体名称
* @return 窗体句柄
*/
public static WinDef.HWND findWindowByEnum(String className, String windowName) {
final Pointer[] result = new Pointer[1];
User32.INSTANCE.EnumWindows(new WinUser.WNDENUMPROC() {
public boolean callback(WinDef.HWND hwnd, Pointer data) {
byte[] buffer = new byte[1024];
User32.INSTANCE.GetClassName(hwnd, buffer, buffer.length);
String clsName = Native.toString(buffer);
if (clsName.contains(className)) {
buffer = new byte[1024];
User32.INSTANCE.GetWindowText(hwnd, buffer, buffer.length);
String winText = Native.toString(buffer);
if (winText.contains(windowName)) {
result[0] = hwnd.getPointer();
return false;
}
}
return true;
}
}, null);
return result[0] == null ? null : new WinDef.HWND(result[0]);
}
}
```
使用示例:
```java
WinDef.HWND hwnd = WindowUtils.findWindow("Notepad", "Untitled - Notepad");
WinDef.HWND childHwnd = WindowUtils.findWindowEx(hwnd, "Edit", null);
System.out.println(childHwnd);
WinDef.HWND hwnd2 = WindowUtils.findWindowByEnum("Notepad", "Untitled - Notepad");
WinDef.HWND childHwnd2 = WindowUtils.findWindowEx(hwnd2, "Edit", null);
System.out.println(childHwnd2);
```
阅读全文