Java – use JNA to get getforegroundwindow();

I once asked a similar question( https://stackoverflow.com/questions/5206633/java-find-out-what-application-window-is-in-focus )But I was guided to use JNI, and I didn't have much success... I have read some tutorials, and some work normally. Others haven't been able to get the information I need. This is the title of the foreground window

Now I'm studying JNA, but I don't know how to access getforeroundwindow()... I think I can print text. Once I get the handle of the window, use this code (found on another thread):

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

    }
}

Any suggestions? thank you!

Solution

How to simply add a method call to match the local GetForegroundWindow to your interface, like this:

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,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,512);
      System.out.println(Native.toString(windowText));
   }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>