Is there any other way to get foreground window title in macOS other than AppleScript

651 Views Asked by At

I want to get the foreground window title in macOS.

I have tried using AppleScript for this, it works but is very slow.

Here is the AppleScript code:

tell application "System Events"
    set frontApp to name of first application process whose frontmost is true
end tell
tell application frontApp
    if the (count of windows) is not 0 then
        set window_name to name of front window
    end if
end tell

It takes a lot of time when we run this using Java.

Is there any other efficient solution to this?

2

There are 2 best solutions below

0
Ted Wrigley On

I haven't used Java in ages, so I don't remember how it accesses frameworks (assuming I ever knew), but the framework you want is Quartz Window Services. These methods give you access to the window server, which manages all of the onscreen windows.

4
wch1zpink On

This AppleScript code works for me using the latest version of macOS Mojave.

For me, this AppleScript code is lightning fast.

try
    tell application "System Events" to tell (process 1 whose it is frontmost) ¬
        to tell (window 1 whose value of attribute "AXMain" is true) ¬
        to set windowTitle to value of attribute "AXTitle"
end try