So you have an NSStatusItem, and you want it to pop a dialog for whatever reason, perhaps a settings window. Where should that dialog be positioned? If you’re not placing it centered on the main screen, you probably want it under the status item itself. How does one get it there?
The basic answer is surprisingly simple.
If you’re like me, you want your dialog to be positioned directly underneath the status item that spawned it. This makes it obvious to the user, and it simply looks nice. Unfortunately, however, Cocoa doesn’t give you an obvious way to get the position of the status item on the menu bar, which makes it a bit more difficult to determine your target position.
Since you probably received the action that spawns your dialog from a menu item, however, you can get around the problem. Just have a look at the window associated with the current event, and off you go:
- (IBAction)myEvent:(id)sender {
NSRect frame = [[[NSApp currentEvent] window] frame];
NSSize origin = [[NSScreen screens][0] visibleFrame].size;
[myDialogWindow setFrameTopLeftPoint:NSMakePoint(frame.origin.x, origin.height)];
// ... and whatever else you need to display your window.
}
This code will position the window just beneath the menu bar, right at the left edge of your status item. There are additional tweaks you’ll want to make, of course, such as ensuring there’s actually enough room to display your entire window, but I’ll leave that as an exercise for the reader.
Enjoy!
S.

11 Responses to Centering A Dialog Under A Status Item In Cocoa