dhrm
dhrm

Reputation: 14944

Cocoa window - how to position in top right

I need to position my NSWindow in the top right of the screen, just below the menubar (like notifications). What is the best approach for doing this?

Upvotes: 3

Views: 4777

Answers (2)

Neha
Neha

Reputation: 1751

You can set the window position to top right corner using:

- (void)setWindowPosition
{
    NSPoint pos;
   pos.x = [[NSScreen mainScreen] visibleFrame].origin.x + [[NSScreen mainScreen] visibleFrame].size.width - [_window frame].size.width ;
    pos.y = [[NSScreen mainScreen] visibleFrame].origin.y + [[NSScreen mainScreen] visibleFrame].size.height - [_window frame].size.height  ;
   [_window setFrameOrigin : pos];
}

Call this method in your applicationDidFinishLaunching:, and also register the windowDidResizeNotification to handle the resize event as:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    [self setWindowPosition];   //set window pos

   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:NSWindowDidResizeNotification object:nil];    //register resize notification

}

Now in your notification handler method, again update the window position.

- (void)handleNotification: (id) sender
{
     [self setWindowPosition];
}

Upvotes: 11

trojanfoe
trojanfoe

Reputation: 122458

Use [NSScreen visibleFrame]:

(untested)

// Assumes self is the NSWindow subclass
NSRect sf = [[NSScreen mainScreen] visibleFrame];
NSRect wf = self.frame;
self.frame = NSMakeRect(NSWidth(sf) - NSWidth(wf), NSHeight(sf) - NSHeight(wf),
                        wf.size.width, wf.size.height);

Upvotes: 1

Related Questions