Centering a Window

When my application opens an initial 800x600 window I resize the window to 80% of the available space for example.

If I set the document placement to Mainscreen a good deal of the window is offscreen so I have been just setting it to default which places it offset upper left.

Is there an option that centres the window?

Two ways:

  1. If you’re already reading the width and the height of the screen to resize the window, you can do some more math to center the window in that screen.

[code]Dim tScreen as screen = screen( 0 )

Dim newFrame as new realbasic.rect( 0, 0, tScreen.availableWidth * 0.8, tScreen.availableHeight * 0.8 )

newFrame.left = ( ( tScreen.availableWidth - newFrame.width ) * 0.5 ) + tScreen.availableLeft
newFrame.top = max( ( ( tScreen.availableHeight - newFrame.height ) * 0.5 ) + tScreen.availableTop, tScreen.availableTop )

me.bounds = newFrame[/code]
I use Available so it’s centered in the available space, and clamp it so that it doesn’t go under the menubar. This solution is x-plat

  1. Use a macOS declare to center the window.

declare sub NSWindowCenter lib "AppKit" selector "center" ( NSWindowInstance as integer ) NSWindowCenter( me.handle )

Thanks Sam :slight_smile:

The first method is great as it is x-plat but have you noticed if you have the dock at the bottom it runs in behind it?

I can adjust it from what you have given above but I noticed it before that available doesn’t always get it right when the dock is enlarged (maybe)

Available is meant to take the dock size into consideration.

I dont have the dock visible on any of my machines, which is why I didn’t notice it.