NSWorkspace's 'frontmostApplication' doesn't change after initial use
Asked Answered
P

2

2

I'm trying to get an update of the current active (foreground) application. Even across computer screens. I'm using this code to try to do it:

print(NSWorkspace.sharedWorkspace().frontmostApplication?.localizedName)

This loops in a command line application every 3 seconds, and prints to console. It works with any application open as active when it first starts up.

However, it does not change from the first app afterwards. 1. Why is it doing this? 2. What is the proper code to make it work? 3. Is there a way to simply get the app name every time the forefront application changes? (preferably in swift or obj-c)

Prizefight answered 11/9, 2015 at 23:29 Comment(2)
What is computer? — Also, what do you mean "loops in a command line application"? Show what you're actually doing. Don't talk about it - show it.Rothrock
Sorry that was stupid of me, edited.Prizefight
R
3

Is there a way to simply get the app name every time the forefront application changes?

Use the NSWorkspace notification NSWorkspaceDidActivateApplicationNotification.

Rothrock answered 12/9, 2015 at 15:49 Comment(0)
B
0

The problem is that you're not running your code in a RunLoop. For example

import AppKit


while true {
    print("app: " + (NSWorkspace.shared.frontmostApplication?.executableURL?.lastPathComponent ?? ""))
    sleep(1)
}

This code does not update the frontmost application, because NSWorkspace does not process events in the background.

But if you use a RunLoop like

func printApp() {
    print("app: " + (NSWorkspace.shared.frontmostApplication?.executableURL?.lastPathComponent ?? ""))
}

Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
        printApp()
}

RunLoop.current.run()

it works as expected. In C/C++ you can use CFRunLoopRun(). For the 3rd point see Matt's answers.

Blockbuster answered 13/6, 2024 at 10:19 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.