Centering A Dialog Under A Status Item In Cocoa

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.



About Steve

When it comes to the desktop, Steve is a former Amiga, Windows, and Linux user, and as of six years ago, a die-hard Mac head (who, for once, isn't thinking of changing platforms again any time soon). When it comes to the server, Linux is pretty much the only game he plays. He also enjoys hardware hacking, and shouldn't be allowed near a keyboard after the sun sets (or for that matter, after it rises. Don't say I didn't warn you).
This entry was posted in Cocoa, Mac Hacking. Bookmark the permalink.

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

  1. Howdy! Do you use Twitter? I’d like to follow you if that would be okay.
    I’m undoubtedly enjoying your blog and look forward to
    new posts.

  2. I’ve been browsing on-line more than three hours nowadays, yet I by no means discovered any fascinating article like yours.
    It’s beautiful value sufficient for me. In my opinion, if all site owners and bloggers made just right content as you probably did, the net
    will likely be much more useful than ever before.

  3. 94Gayle says:

    Hi admin, i must say you have high quality posts here.
    Your website should go viral. You need initial traffic only.

    How to get it? Search for: Mertiso’s tips go viral

Leave a Reply

Your email address will not be published. Required fields are marked *