Thursday, May 29th, 2008

Centering an Application or Window In AIR

By Javier Julio

I’ve run into several AIR applications that don’t center the main window on your desktop by default. This positioning is something I would prefer because I’ve had many AIR applications that have installed partially hidden under my OSX dock.

Originally, I came across a simple way of centering a window by doing the following on the applicationComplete event:

var rect:Rectangle = new Rectangle();
var maxSize:Point = new Point(Capabilities.screenResolutionX, Capabilities.screenResolutionY);
rect.width = 700;
rect.height = 570;
rect.x = (maxSize.x - rect.width) / 2;
rect.y = (maxSize.y - rect.height) / 2;
stage.nativeWindow.bounds = rect;

If you add the above block in your MXML component containing the WindowedApplication tag, you won’t need to import anything for the centering to take place. However, you do need to apply it on the applicationComplete event, otherwise an error occurs on the last line.

Recently, though, I came across a sample in the Adobe Flex LiveDocs where a much shorter snippet performs the same desired functionality and works in all three events: initialize, creationComplete and applicationComplete.

var screenBounds:Rectangle = Screen.mainScreen.bounds;
nativeWindow.x = (screenBounds.width - nativeWindow.width) / 2;
nativeWindow.y = (screenBounds.height - nativeWindow.height) / 2;
Leave a Comment