Duck
Duck

Reputation: 35953

Performing an action when _statusItem is clicked, with a NSMenu and the window not in focus seems impossible

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.

Upvotes: 0

Views: 209

Answers (1)

CRD
CRD

Reputation: 53000

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.

Upvotes: 1

Related Questions