Task: The program should monitor the active windows in the Windows system and write them to the HashMap as a key. And the value of this key will be the time during which this window was active.
Question: How can I get this window by Java (or by other means, the result of which can be transferred to Java)? It will only be necessary to monitor the active windows and record the total time of their work.

  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

Windows can be found like this:

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

To get window status you need to use the function from user32:

 GetWindowLong 

Using this function, you can get visible windows as follows:

 int visibleWindow = WS_BORDER | WS_VISIBLE; if ((GetWindowLong(hwnd, GWL_STYLE) & visibleWindow) == visibleWindow) { // если истина, то окно видно } 
  • and how then to get the list of open windows in Window []? - Vladislav
  • @ Vladislav I rewrote the answer, check out. - Mstislav Pavlov
  • Thank! And this is the only way? Maybe there is something simpler?) - Vladislav
  • @ Vladislav, the bottom line is that only OSes can provide this data. So even if you solve this problem in another language, you will have to resort to the same method. - Mstislav Pavlov
  • I understood you, thanks for the help! :) - Vladislav