Search code examples
applescriptforeground

Applescript get application from second desktop


I am trying to get the foreground application from my second monitor (In Mavericks, second desktop). Here's my code that only gets the foreground application:

tell application "System Events"
set frontApp to name of first application process whose frontmost is true
end tell

How can I change it so it gets the application from a specific desktop / screen?


Solution

  • I don't think you can do as you want. If you look at the properties of frontApp there is no property that would indicate which screen it is on. However, what you can do is check the location of the application's windows. If you get the properties of a window of a process then you will see that it has a "position" property. You could check those coordinates to determine which screen it is on.

    For example, I have 2 screens. My laptop is setup to be the main screen. I know the screen resolution of the main screen is 1680x1050. Therefore, if I check a window and it has a position outside of those coordinates then I know it must be on the second monitor. Here's how I could do that.

    NOTE: I can tell which applications have windows on the second monitor, but not which application on the second monitor is frontmost... like you asked. You'll have to figure something else out for that. I'm showing you this as an idea that maybe you can make workable for your situation.

    Here I am only getting the first application with a window on the second monitor. This should show you the idea and you can adjust the code to do as you need.

    set mainScreenResX to 1680
    set mainScreenResY to 1050
    
    tell application "System Events"
        set firstFoundAppOnSecondScreen to missing value
    
        set visibleApps to application processes whose visible is true
        repeat with visibleApp in visibleApps
            try
                tell visibleApp
                    set {x, y} to position of window 1
                    if x > mainScreenResX or x < 0 or y > mainScreenResY or y < 0 then
                        set firstFoundAppOnSecondScreen to name
                        exit repeat
                    end if
                end tell
            end try
        end repeat
    
        return firstFoundAppOnSecondScreen
    end tell