Reputation: 65
I have a background process running on the user’s macOS machine. Its job is to detect whenever any app is launched on the machine. Currently, I am detecting the NSNotificationCenter
’s NSWorkspaceDidLaunchApplicationNotification
event. This works perfectly for detecting when an app is freshly launched (i.e. the app had no instance already running at that time).
But, on macOS, if we click the red cross button at the top-left corner, it generally closes the app window and the app continues to run in the background. This is also evident by the app icon visible on the dock with the dot indicator below it. If I click the app icon on the dock and then launch it, the NSWorkspaceDidLaunchApplicationNotification
event won’t be triggered.
To track such events, I tried using the NSWorkspaceDidActivateApplicationNotification
event. Using this event, I was able to detect all the app launch scenarios. The problem is that this event gets triggered whenever the app comes into focus such as switching windows using command+tab, clicking on its dock icon, changing between two apps, …
Is there a way to filter out these triggers or identify which action led to the trigger? Or is there some other event/ method I can listen to which gives the required filtered triggers? I only want to detect scenarios where a new window of the app is created.
Upvotes: 1
Views: 1213
Reputation: 1384
What you seems to want is two different things, as was mentioned in comments, which should be processed separately to be reached.
To detect app launch, when the new process is started. You could use the NSWorkspaceDidLaunchApplicationNotification if it is enough (usually for visual user apps), or kqueue if it is not, or even EndpointSecurity framework to rule them all.
To track the window(s) in the already launched app. Visually, if the white dot under app dock icon is there, the app is still launched. There is an Accessibility framework for this task, you could track the event of window creation, window destruction, get count of windows from target process id, visibility state and etc. It is a bit abandoned and has no updates since maybe release, but it will work for you in most cases.
Upvotes: 1