Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get titles of Non-Java Windows in Java

Tags:

java

windows

Window.getWindows();

Doesn't get all the open windows, just the java ones. Is there a way to get all the windows the operating system has open. I'm making a java taskbar.

like image 935
user698816 Avatar asked Jun 16 '12 22:06

user698816


2 Answers

There is no solution using core Java, but the problem can be solved using JNI or for an easier time, JNA. As noted in the comments, no solution (that I know of) will be platform independent.

For instance, this demo program uses JNA to enumerate all Windows with title in a Windows platform, but will also include windows that are not top-level windows and even windows that aren't visible:

import java.util.ArrayList;
import java.util.List;

import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.win32.StdCallLibrary;

public class EnumAllWindowNames {
   static interface User32 extends StdCallLibrary {
      User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class);

      interface WNDENUMPROC extends StdCallCallback {
         boolean callback(Pointer hWnd, Pointer arg);
      }

      boolean EnumWindows(WNDENUMPROC lpEnumFunc, Pointer userData);
      int GetWindowTextA(Pointer hWnd, byte[] lpString, int nMaxCount);
      Pointer GetWindow(Pointer hWnd, int uCmd);
   }

   public static List<String> getAllWindowNames() {
      final List<String> windowNames = new ArrayList<String>();
      final User32 user32 = User32.INSTANCE;
      user32 .EnumWindows(new User32.WNDENUMPROC() {

         @Override
         public boolean callback(Pointer hWnd, Pointer arg) {
            byte[] windowText = new byte[512];
            user32.GetWindowTextA(hWnd, windowText, 512);
            String wText = Native.toString(windowText).trim();
            if (!wText.isEmpty()) {
               windowNames.add(wText);
            }
            return true;
         }
      }, null);

      return windowNames;
   }

   public static void main(String[] args) {
      List<String> winNameList = getAllWindowNames();
      for (String winName : winNameList) {
         System.out.println(winName);
      }
   }


}
like image 159
Hovercraft Full Of Eels Avatar answered Nov 13 '22 13:11

Hovercraft Full Of Eels


Addition to @Hovercraft Full Of Eels, if you also have windows which are titled with unreadable characters and get "?" printed for those characters, try to:

  • convert byte[] to string by using different encoding (as I understood)

see below:

String wText = Native.toString(windowText, "windows-1254").trim();

Possible encodings instead of "windows-1254 (which worked well for Turkish characters)":

  • UTF-8
  • UTF-16
  • ASCII
  • ISO-8859-1
  • ...
like image 29
MBDNC Avatar answered Nov 13 '22 11:11

MBDNC