Skip to content

Center a Window Using a macOS Declare

You can call into Cocoa APIs to use methods and properties that are not built into the Xojo framework by using the Declare command. To create a Declare statement you first need to track down the API you want to use using Apple’s documentation: Apple Developer Documentation.

Most of the time you will reference the Foundation and AppKit libraries, but there are many other libraries as well. Xojo Declares use the Objective-C names so be sure to refer to those in the documentation rather than the Swift naming.

When you call Cocoa methods, you supply the method name using the Selector part of the Declare command. The selector name has to end in a “:” if there are any parameters that are passed, an oddity of how Objective-C works. Unlike with Xojo methods, the case of the name also has to match exactly. For the Xojo Declare, the first parameter is always required and must be a reference to the class containing the method you are calling.

To start with a simple example, consider that you may to center a window on the screen. You can obviously do this by manually adjusting the window’s Top and Left properties by taking into account the window size and the screen size, but Cocoa has a simple center function that can be used on a window.

On macOS, a Xojo window is actually a native NSWindow. When you view Apple’s docs for NSWindow you’ll see there is a center method. This method is very simple as it does not take any parameters. Looking at the doc page you should note that this function is in the AppKit library. Now you can create a Declare command to map to the center method:

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

Remember, even though the center method does not take any parameters, you still have to add a parameter to the Declare so you can pass in the reference to the calling class, which in this case is the window to center.

You can call this method like this (such as from a button’s Action event handler):

centerWindow(Self.Handle)

Because this method is called for a window, you can put it in a Xojo Extension Method to make it easier to call. To do this, create a global method on a module like this:

Public Sub Center(Extends w As Window)
  #If TargetMacOS Then
    Declare Sub centerWindow Lib "AppKit" Selector "center" (windowHandle As Integer)
    centerWindow(w.Handle)
  #EndIf
End Sub

Note the use of the “#If TargetMacOS” line. This prevents this code from being compiled into Windows or Linux builds of your app where the code could possibly crash your app.

This now allows you to have code like this on a window’s Open event to center the window:

Self.Center

To learn more about macOS Declares: