gpt4 book ai didi

java - JAVA返回HWND的方法

转载 作者:行者123 更新时间:2023-11-29 05:11:51 25 4
gpt4 key购买 nike

附件代码根据标题搜索窗口,如果存在则激活。

   public static void ActivateWindow() {
User32.INSTANCE.EnumWindows(new WNDENUMPROC() {

@Override
public boolean callback(HWND hWnd, Pointer arg1) {
char[] windowText = new char[512];
User32.INSTANCE.GetWindowText(hWnd, windowText, 512);
String wText = Native.toString(windowText);

String title = "Chrome";
if (wText.contains(title))
{
User32.INSTANCE.ShowWindow(hWnd, 9); //activeWindow()
User32.INSTANCE.SetForegroundWindow(hWnd); //activeWindow()
}

return true;

}
}, null);
}

我的目标是拆分 ActivateWindow() 方法。

如果窗口存在,IsWindowOpen() 将返回 HWND 对象,而 activateWindow() 将激活 HWND。

我找不到在回调中返回 HWND 的方法?

最佳答案

至少有两种方式

使用实例变量:
如果您使方法成为非静态方法,则可以在回调中访问实例变量。
看下面例子中foundWindow的用法:

public class JNA_Test {
HWND foundWindow = null;

public static void main(String[] args) {
JNA_Test jna = new JNA_Test();
if(jna.isWindowOpen("chrome")){
jna.activateWindow();
}
}

public void activateWindow() {
if(foundWindow != null) {
User32.INSTANCE.ShowWindow(foundWindow, 9);
User32.INSTANCE.SetForegroundWindow(foundWindow);
}
}

public boolean isWindowOpen(String title) {
foundWindow = null;
User32.INSTANCE.EnumWindows(new WNDENUMPROC() {

@Override
public boolean callback(HWND hWnd, Pointer arg1) {
if(foundWindow == null) {
char[] windowText = new char[512];
User32.INSTANCE.GetWindowText(hWnd, windowText, 512);
String wText = Native.toString(windowText);
if (wText.contains(title)) {
foundWindow = hWnd;
}
}
return true;

}
}, null);

return foundWindow != null;
}
}


使用 JNA 指针:
在这个例子中,不管方法是否是静态的。
看看foundWindowPointer的用法:

public class JNA_Test2 {

public static void main(String[] args) {
Pointer foundWindowPointer = new Memory(Pointer.SIZE);
JNA_Test2.isWindowOpen("chrome", foundWindowPointer);
if (foundWindowPointer.getPointer(0) != null) {
HWND foundWindow = new HWND(foundWindowPointer.getPointer(0));
JNA_Test2.activateWindow(foundWindow);
}
}

public static void activateWindow(HWND foundWindow) {
if (foundWindow != null) {
User32.INSTANCE.ShowWindow(foundWindow, 9);
User32.INSTANCE.SetForegroundWindow(foundWindow);
}
}

public static void isWindowOpen(String title, Pointer foundWindowPointer) {
User32.INSTANCE.EnumWindows(new WNDENUMPROC() {

@Override
public boolean callback(HWND hWnd, Pointer foundWindowPointer) {
if (foundWindowPointer != null) {
char[] windowText = new char[512];
User32.INSTANCE.GetWindowText(hWnd, windowText, 512);
String wText = Native.toString(windowText);
if (wText.contains(title)) {
foundWindowPointer.setPointer(0, hWnd.getPointer());
}
}
return true;

}
}, foundWindowPointer);
}
}

关于java - JAVA返回HWND的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28171948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com