你好~我正在使用JNA,我想让另一个程序在屏幕上显示焦点,但它不起作用。
这是我的代码。
import java.util.Scanner;
导入com.sun.jna.platform.win32.User32;
导入com.sun.jna.platform.win32.WinDef; 公共(public)类主要{
public static void main(String args[]) {
System.out.println("test");
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
sc.close();
System.out.println(number);
setFocusToWindowsApp("점포관리", number);
System.exit(0);
}
public static void setFocusToWindowsApp(String applicationTitle, int windowState) {
//int state = User32.SW_SHOWNORMAL; // default window state (Normal)
int state = windowState;
switch (state) {
default:
case 0:
state = User32.SW_SHOWNORMAL;
break;
case 1:
state = User32.SW_SHOWMAXIMIZED;
break;
case 2:
state = User32.SW_SHOWMINIMIZED;
break;
}
User32 user32 = User32.INSTANCE;
WinDef.HWND hWnd = user32.FindWindow(null, applicationTitle);
if (user32.IsWindowVisible(hWnd)) {
user32.ShowWindow(hWnd, state); // .SW_SHOW);
user32.SetForegroundWindow(hWnd);
user32.SetFocus(hWnd);
}
}
}
此代码仅用于测试...没有扫描仪,它工作得很好。 但对于扫描仪,只有 SW_SHOWMAXIMIZED 有效。否则,该程序就不会出现在屏幕上。它只是在图标栏上闪烁。我认为 Scanner 与系统调用或其他什么相关,所以它扰乱了 user32。我认为。我尝试了文档上的每个标志。(SW_SHOWNORMAL,SW_SHOWMAXIMIZED等...)但只有SW_SHOWMAXIMIZED有效..我不希望窗口最大化。
任何帮助将不胜感激..谢谢!!
最佳答案
正如您所假设的那样,问题的原因在于扫描仪。
但问题不在于 showWindow() 函数,而是在于 SetForegroundWindow() 函数。
文档说明如下:
An application cannot force a window to the foreground while the user is working with another window. Instead, Windows flashes the taskbar button of the window to notify the user.
因此,如果您需要输入,则无法将此屏幕从应用程序带到前台。
该解决方案有点破解,但只需使屏幕首先最小化,然后恢复到正常 View ,您就可以将其强制到前台。
修改后的方法如下所示
public static void setFocusToWindowsApp(String applicationTitle, int windowState) {
int state = windowState;
switch (state) {
default:
case 0:
state = User32.SW_SHOWNORMAL;
break;
case 1:
state = User32.SW_SHOWMAXIMIZED;
break;
case 2:
state = User32.SW_SHOWMINIMIZED;
break;
}
User32 user32 = User32.instance;
HWND hWnd = user32.FindWindowA(null, applicationTitle);
if (user32.IsWindowVisible(hWnd)) {
if (state != User32.SW_SHOWMINIMIZED) {
user32.ShowWindow(hWnd, User32.SW_SHOWMINIMIZED);
}
user32.ShowWindow(hWnd, state);
user32.SetFocus(hWnd);
}
}
关于java - JNA user32.ShowWindow 与 java.util.Scanner 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54821655/