About Centering a Window

I am surprised to find that the result of the two routines give different positions! The window is not placed exactly in the same place!
Does anyone have an explanation?

Declare Sub centerWindow Lib "AppKit" Selector "center" (windowHandle As Ptr)


Self.Left = (screen(0).Width - Self.Width) / 2
Self.top = (screen(0).Height - Self.Height) / 2

What is the difference?

Use AvailableWidth and AvailableHeight.

1 Like

See Apple documentation. It states for center:

The window is placed exactly in the center horizontally and somewhat above center vertically. Such a placement carries a certain visual immediacy and importance.

For easy reproduction of the effect make a new project and add a button with following code in pressed event:

Declare Sub centerWindow Lib "AppKit" Selector "center" (windowHandle As Ptr)

Self.Title = "centerWindow"

Dim w As New Window1
w.Left = (Screen(0).Width - w.Width) / 2
w.top = (Screen(0).Height - w.Height) / 2
w.Title = "calculated"

See the difference !

Maybe Apple uses the Golden Ration (factor 0.618?).

Another thing to bear in mind is if you want to center the window contents, or the entire frame including title area and border. You’re only showing how you come up with the center of the screen, and not how you would place the window in the “center” if not using the declare. A common assumption is when people use the window .Top, .Left, etc but contrast that to the window bounds property.

Each has a purpose; but you need to be aware of the difference and what suits a given scenario.