繁体   English   中英

使用JNA获取GetForegroundWindow();

[英]Using JNA to get GetForegroundWindow();

我在前一个帖子( https://stackoverflow.com/questions/5206633/java-find-out-what-application-window-is-in-focus)上问了一个类似的问题,但我被引导使用JNI,我我没有取得多大成功...我已经阅读了一些教程,虽然有些工作正常,但其他人却没有,我仍然无法获得我需要的信息,这是前景窗口的标题。

现在我正在研究JNA,但我无法弄清楚如何访问GetForegroundWindow()...我想我可以使用此代码(在另一个线程上找到)获取窗口句柄后打印文本:

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));

    }
}

有什么建议么? 谢谢!

如何简单地添加方法调用以将本机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文件中(至少在v3.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库中的所有功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM