我在前一个线程上提出了一个类似的问题( https://stackoverflow.com/questions/5206633/java-find-out-what-application-window-is-in-focus),但我被引导使用JNI,而我没有太多的成功…我已经阅读了一些教程,虽然有些工作正常,但其他人不能得到我需要的信息,这是前台窗口的标题。
现在我正在研究JNA,但我不知道如何访问GetForegroundWindow()…我想我可以打印文本,一旦我得到了处理窗口使用此代码(在另一个线程上find):
import com.sun.jna.*; import com.sun.jna.win32.*; public class jnatest { public interface User32 extends StdCallLibrary { User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class); int GetWindowTextA(PointerType hWnd, byte[] lpString, int nMaxCount); } public static void main(){ byte[] windowText = new byte[512]; PointerType hwnd = //GetForegroundWindow() (?)... User32.INSTANCE.GetWindowTextA(hwnd, windowText, 512); System.out.println(Native.toString(windowText)); } }
有什么build议么? 谢谢!
如何简单地添加一个方法调用来匹配原生的GetForegroundWindow到你的接口,如下所示:
import com.sun.jna.*; import com.sun.jna.platform.win32.WinDef.HWND; import com.sun.jna.win32.*; public class JnaTest { public interface User32 extends StdCallLibrary { User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class); HWND GetForegroundWindow(); // add this int GetWindowTextA(PointerType hWnd, byte[] lpString, int nMaxCount); } public static void main(String[] args) throws InterruptedException { byte[] windowText = new byte[512]; PointerType hwnd = User32.INSTANCE.GetForegroundWindow(); // then you can call it! User32.INSTANCE.GetWindowTextA(hwnd, windowText, 512); System.out.println(Native.toString(windowText)); } }
如果获得窗口标题是你想要做的,你不必显式加载user32
库。 JNA自带的platform.jar
文件(至少在3.4版本中)。
我在这里工作:
import com.sun.jna.Native; import com.sun.jna.platform.win32.WinDef.HWND; import com.sun.jna.platform.win32.User32; public class JnaApp { public static void main(String[] args) { System.out.println("title is " + getActiveWindowTitle()); } private static String getActiveWindowTitle() { HWND fgWindow = User32.INSTANCE.GetForegroundWindow(); int titleLength = User32.INSTANCE.GetWindowTextLength(fgWindow) + 1; char[] title = new char[titleLength]; User32.INSTANCE.GetWindowText(fgWindow, title, titleLength); return Native.toString(title); } }
在User32的Javadoc上查看更多信息。 它获得了user32库中几乎所有的功能。