0

There are similar questions on SO but this have a twist.

I need to trigger an action when the user clicks on my app icon sitting on the menu bar. The action is to bring its window to the front, or in other words,

  [[[NSApplication sharedApplication] keyWindow] makeKeyAndOrderFront:self];

Normally I would do this:

[_statusItem setTarget:self];
[_statusItem setAction:@selector(bringToFront:)];

but this _statusItem has a NSMenu.

If I disable the menu, bringToFront: is triggered.

So I thought, I will implement NSMenuDelegate method menuWillOpen.

- (void)menuWillOpen:(NSMenu *)menu {
  [[[NSApplication sharedApplication] keyWindow] makeKeyAndOrderFront:self];
}

But there is a problem. This will work if the app window is the one selected, but suppose the app is running and I select safari. Then, my app's window is not in focus anymore, is behind 2000 Safari windows. Now I click on my app's icon on the menu bar and menuWillOpen will not be triggered.

If I want to bring the window to focus by clicking on the app's icon on the menu bar, having to bring the window to focus to make it work does not make sense.

Duck
  • 34,902
  • 47
  • 248
  • 470
  • `NSApplication` notifications are posted in response to your app gaining/resigning active status. Have you tried enabling/disabling your status item's menu in response to these? – CRD Jul 16 '17 at 05:15
  • how do I do that? – Duck Jul 16 '17 at 05:16
  • Do what part? Read the `NSApplication` documentation for details of the notifications. – CRD Jul 16 '17 at 05:18
  • I am not seeing how it can help. I want to make the app active by clicking on the menu, not selecting an item from it. Anyway, thanks. – Duck Jul 16 '17 at 05:20
  • You wrote "If I disable the menu, bringToFront: is triggered" so I wondered whether you'd tried disabling it when your app resigned active status... – CRD Jul 16 '17 at 05:41
  • Ah, I see. I will try that and let you know. – Duck Jul 16 '17 at 05:44
  • Brilliant! Please make your comment an answer, so I can accept! THANKS – Duck Jul 16 '17 at 05:52

1 Answers1

1

NSApplication notifications are posted in response to your app gaining/resigning active status. Handle these notifications and enable/disable your status item's menu so that your action gets invoked when your app is in the background.

CRD
  • 52,522
  • 5
  • 70
  • 86