System Tray Icon and Menu for an Adobe Flex AIR Application

Adobe AIR allows you to set up a system tray icon and context menu for your application. In true AIR & Flex style, this is surprisingly simple to achieve and doesn’t even require a .ico file.

Creating the System Tray Icon

Within the WindowedApplication we can embed a graphic to be used as the icon. I’m using a 16 x 16 PNG with full alpha transparency.

[Embed(source="icons/tray.png")]

private var TrayIcon:Class;

By attaching a handler to the initialize event, an instance of the embedded image is created (cast to a Bitmap) and the bitmap data extracted. This data can then be assigned to the array of icons for the application. I’m also setting the tooltip text. This code is wrapped inside a check that the system support system tray icons.

if (NativeApplication.supportsSystemTrayIcon) {
    var trayIcon:BitmapData = Bitmap(new TrayIcon()).bitmapData;
    SystemTrayIcon(nativeApplication.icon).bitmaps = [trayIcon];
    SystemTrayIcon(nativeApplication.icon).tooltip = 'This text will appear when hovering over the icon';
}

The icon also supports event handlers for various ScreenMouseEvent types, meaning you can handle clicks, right clicks and so on, depending on your requirements.

Creating a Context Menu

The context menu for the tray icon is created as a standard NativeMenu (with a number of NativeMenuItem items) and then assigned as the menu for the icon. The sample below defined a menu with an exit option which is handled by a separate handler function.

var menu:NativeMenu = new NativeMenu();

var exitMenuItem:NativeMenuItem = new NativeMenuItem("Exit");
exitMenuItem.addEventListener(Event.SELECT, exitApplication);
menu.addItem(exitMenuItem);

SystemTrayIcon(nativeApplication.icon).menu = menu;

The menu will now appear on a right click on the tray icon, there is no need to explicitly wire this interaction together.

Tags: , , , , ,

Leave a Comment