【发布时间】:2016-05-25 10:38:36
【问题描述】:
我正在尝试让我的应用程序能够聚焦另一个窗口(在本例中为记事本)
我的班级是这样的
public static class Win32WindowUtils {
public interface User32 extends StdCallLibrary {
User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class, W32APIOptions.DEFAULT_OPTIONS);
HWND GetParent(HWND hWnd);
HWND FindWindow(String lpClassName, String lpWindowName);
HWND SetFocus(HWND hWnd);
HWND FindWindowEx(HWND hwndParent, HWND hwndChildAfter, String lpszClass, String lpszWindow);
int GetWindowText(HWND hWnd, char[] lpString, int nMaxCount);
}
private static final int WIN_TITLE_MAX_SIZE = 512;
public static HWND GetWindowHandle(String strSearch, String strClass) {
char[] lpString = new char[WIN_TITLE_MAX_SIZE];
String strTitle;
int iFind = -1;
HWND hWnd = User32.INSTANCE.FindWindow(strClass, null);
while(hWnd != null) {
User32.INSTANCE.GetWindowText(hWnd, lpString, WIN_TITLE_MAX_SIZE);
strTitle = new String(lpString);
strTitle = strTitle.toUpperCase();
iFind = strTitle.indexOf(strSearch);
if(iFind != -1) {
return hWnd;
}
hWnd = (User32.INSTANCE).FindWindowEx(null, hWnd, strClass, null);
}
return hWnd;
}
}
我通过以下方式调用它:
User32.INSTANCE.SetFocus(Win32WindowUtils.GetWindowHandle(windowTitle, null));
注意:
public String windowTitle = "Unbennant - Editor";
遗憾的是什么都没发生,我不知道为什么
【问题讨论】:
-
根据MSDN,“窗口必须附加到调用线程的消息队列”。该注释似乎暗示您不能通过
SetFocus()函数强制关注不同的应用程序。 -
您可能想改用BringWindowToTop()。
-
您要激活应用程序(将其放在前面)还是只是确保将键盘事件定向到所选窗口?