Get current active window's title in Java

前端 未结 6 2011
耶瑟儿~
耶瑟儿~ 2020-12-08 17:43

I am trying to write a Java program that logs what application I\'m using every 5 seconds (this is a time tracker app). I need some way to find out what the current active w

6条回答
  •  时光说笑
    2020-12-08 18:27

    Using SWT internals, I was able to put this together, and it seems to work nicely:

        /** @return The currently active window's title */
        public static final String getActiveWindowText() {
            long /*int*/ handle = OS.GetForegroundWindow();
            int length = OS.GetWindowTextLength(handle);
            if(length == 0) return "";
            /* Use the character encoding for the default locale */
            TCHAR buffer = new TCHAR(0, length + 1);
            OS.GetWindowText(handle, buffer, length + 1);
            return buffer.toString(0, length);
        }
    
    public static final void main(String[] args) {
        try {
            Thread.sleep(1000L);
        } catch(InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        System.out.println(getActiveWindowText());
    }
    

    Prints: user interface - Get current active window's title in Java - Stack Overflow - Google Chrome

提交回复
热议问题