簡體   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