2

When a macOS application is already open and running, is there any way for it to detect when its Finder icon is opened?

In that situation, opening its Finder icon causes the application to become active, and I can detect that event using NSNotificationCenter or the application delegate's applicationDidBecomeActive: method.

However, so far I haven't found a way to distinguish that activation event from any of the other ways an application can become active, such as clicking on its window, clicking on its Dock icon, switching to it using command+tab, activating it with AppleScript, and so on. I tried checking to see if any of these circumstances used an apple event to activate the app with [[NSAppleEventManager sharedAppleEventManager] currentAppleEvent], but it returns nil as there is no current apple event, so that doesn't help.

Bri Bri
  • 2,169
  • 3
  • 19
  • 44
  • Assuming you wrote said program, you could have it fire an alert when opened the first time. What is the use-case for this? – Libra Nov 21 '19 at 19:50
  • @Laif The app I'm developing is a background-only launch agent and I'd like to have opening its Finder icon cause its UI to appear. – Bri Bri Nov 21 '19 at 20:56
  • If it's a background-only app, it shouldn't even have a Dock icon. Are you sure that's what you mean? – JWWalker Nov 22 '19 at 21:50
  • Yes my specific app doesn't have a Dock icon most of the time. I'm specifically interested in detecting when its Finder icon has been opened while it has no Dock icon. – Bri Bri Nov 23 '19 at 07:11

1 Answers1

2

The app delegate method -applicationShouldHandleReopen:hasVisibleWindows: is called on such a re-open event.

Note that (re-)opening from the Finder, Launchpad, or Dock is the same, by design.

Ken Thomases
  • 88,520
  • 7
  • 116
  • 154
  • I'll add that it is possible to tell what caused the app to be reopened. You can use `NSAppleEventDescriptor *appleEvent = [[NSAppleEventManager sharedAppleEventManager] currentAppleEvent]` in the `-applicationShouldHandleReopen:hasVisibleWindows:` method to get the apple event that triggered it, then get the pid of the process that sent the apple event using `[[appleEvent attributeDescriptorForKeyword:keySenderPIDAttr] int32Value]`. If the pid matches the pid of the Finder, then it was opening a Finder icon that caused the app to reopen. – Bri Bri Nov 23 '19 at 07:28