0
votes

Im trying to make my NSViews and windows that I create programmatically have a fixed position no matter what the resolution of my screen is and no matter how many displays i have connected to my main desktop. For example if I have an external monitor or if I decide to change my screen resolution I want the NsRect of my NSView or NSWindow to always appear in the same place. Would this work?

NSRect mainFrame = [[NSScreen mainScreen] frame]
NSRect helpFrame = NSZeroRect;
helpFrame.origin.x = (mainFrame.size.width - width) / 2.0;

would that put the x value of my window always in the center no matter what the resolution is? I feel that when I connect an external monitor the resolution changes and the middle of the screen is no longer where I want it. Is NSScreen mainScreen the appropriate thing to call? thanks!

1

1 Answers

1
votes

First of all, what you're asking is ambiguous. What does "same place" mean?

You don't show what width is. Assuming it's the width of the window, what you showed will compute an X location that horizontally centers the window on the "main" screen. However, -mainScreen may not do what you think. If you want the primary display, the one with the menu bar, you want [[NSScreen screens] objectAtIndex:0].

However, even if you set the window's frame using the computation shown, that doesn't keep it centered if the screen configuration changes. You need to observe the NSApplicationDidChangeScreenParametersNotification from the application object and recenter it.

By the way, is there a reason you're not using -[NSWindow center]?