How to get list of all window handles in Java (Using JNA)?

前端 未结 1 370
花落未央
花落未央 2020-12-01 11:17

I am novice for JNA. I am trying to get handles for all the windows including minimised ones. I need HWND of all the windows. I have gone thro the question Wind

相关标签:
1条回答
  • 2020-12-01 12:12

    The latest version of JNA has had some changes that should fix this (as one of the authors of JNA, Luke Quinane, states here). If you use the latest version and check the JNA API, you'll see that the WinUser.WNDENUMPROC interface's method actually uses WinDef.HWND as its parameter, not long or int.

    For example:

    import com.sun.jna.Native;
    import com.sun.jna.Pointer;
    import com.sun.jna.platform.win32.WinDef.HWND;
    import com.sun.jna.platform.win32.WinUser;
    import com.sun.jna.platform.win32.WinUser.WNDENUMPROC;
    import com.sun.jna.win32.StdCallLibrary;
    
    public class TryWithHWND {
       public interface User32 extends StdCallLibrary {
          User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class);
          boolean EnumWindows(WinUser.WNDENUMPROC lpEnumFunc, Pointer arg);
          int GetWindowTextA(HWND hWnd, byte[] lpString, int nMaxCount);
       }
    
       public static void main(String[] args) {
          final User32 user32 = User32.INSTANCE;
          user32.EnumWindows(new WNDENUMPROC() {
             int count = 0;
             @Override
             public boolean callback(HWND hWnd, Pointer arg1) {
                byte[] windowText = new byte[512];
                user32.GetWindowTextA(hWnd, windowText, 512);
                String wText = Native.toString(windowText);
    
                // get rid of this if block if you want all windows regardless of whether
                // or not they have text
                if (wText.isEmpty()) {
                   return true;
                }
    
                System.out.println("Found window with text " + hWnd + ", total " + ++count
                      + " Text: " + wText);
                return true;
             }
          }, null);
       }
    }
    
    0 讨论(0)
提交回复
热议问题