附加代码根据标题搜索窗口并激活它(如果存在)。
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的方法吗?
答案 0 :(得分:2)
至少有两种方式
使用实例变量:
如果使方法非静态,则可以在回调中访问实例变量
在下面的例子中查看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);
}
}
答案 1 :(得分:1)
由于HWND
实际上是“指向某事物的指针”,即void*
,您可能希望在Java端使用jna的com.sun.jna.Pointer
类型。
使用jna的win32平台API时com.sun.jna.platform.win32.WinDef.HWND
更合适,如Handle external windows using java的答案所示。请查看How to get list of all window handles in Java (Using JNA)?以获取其他代码示例。