6

In an app that uses a NSStatusItem with a custom view like this:

enter image description here

... how can you get notifications when:

  1. The status bar gets hidden because of a full screen app
  2. The status item moves position because another item is added/removed/resized?

Both are necessary to move the custom view to the right position when the item changes places.

coneybeare
  • 33,113
  • 21
  • 131
  • 183

1 Answers1

11

There is a method -[NSStatusItem setView:]. When you set a custom view for your status item, this view is automatically inserted into a special status bar window. And you can access that window using a method -[NSView window] to observe its NSWindowDidMoveNotification:

- (void)applicationDidFinishLaunching:(NSNotification *)notification
{
    NSStatusItem *statusItem = [self newStatusItem];
    NSView *statusItemView = [self newStatusItemView];
    statusItem.view = statusItemView;

    NSNotificationCenter *dnc = [NSNotificationCenter defaultCenter];
    [dnc addObserver:self selector:@selector(statusBarDidMove:)
                name:NSWindowDidMoveNotification object:statusItemView.window];
}

- (void)statusBarDidMove:(NSNotification *)note
{
    NSWindow *window = note.object;
    NSLog(@"%@", NSStringFromRect(window.frame)); // i.e. {{1159, 900}, {24, 22}}
}

You will receive the notification every time the status bar becomes visible or hidden and when your icon is moved. This is your chance to update a location of your popup panel.

Vadim
  • 9,383
  • 7
  • 36
  • 58
  • It would be nice if the NSWindowWillMoveNotification was called here too, but unfortunately it is not. Maybe in a future OS release. – coneybeare Jul 17 '12 at 12:07
  • Usually, the status bar changes its state when you activate another frontmost app. And if you develop a menu bar helper app, then most likely the popup panel become invisible at the moment when the status bar moves. If this is the case, you can safely avoid all handling. – Vadim Jul 17 '12 at 12:58
  • I have an app with a use case to keep the panel showing at certain times, even when the app is not foremost. That is why I need this – coneybeare Jul 17 '12 at 13:03
  • Then I would recommend to just perform a smooth popup animation to the new location on `NSWindowDidMoveNotification`, it should feel great. – Vadim Jul 17 '12 at 20:00
  • Thanks. Care to take a crack at my next issue? http://stackoverflow.com/questions/11525426/custom-nsstatusitem-and-nsview-not-reliably-receiving-nstrackingevents – coneybeare Jul 17 '12 at 21:31
  • Can anyone confirm this is still working in Yosemite or later? I am not receiving the notification. – Will Oct 20 '15 at 13:40