Wednesday, April 13, 2011

Working with menus in AIR: Part 6

Today we are going to learn how to set hotkeys for menu items in our AIR application.

Here's the code we have so far:

import flash.display.NativeMenu;
import flash.display.NativeMenuItem;
import flash.events.Event;

var myMenu:NativeMenu = new NativeMenu();

if (NativeWindow.supportsMenu)
{
stage.nativeWindow.menu = myMenu;
}
if (NativeApplication.supportsMenu)
{
NativeApplication.nativeApplication.menu = myMenu;
}

var item:NativeMenuItem = new NativeMenuItem("Hello!");
myMenu.addItem(item);

var mySubMenu:NativeMenu = new NativeMenu();

var subitem1:NativeMenuItem = new NativeMenuItem("Red");
var subitem2:NativeMenuItem = new NativeMenuItem("Blue");
var subitem3:NativeMenuItem = new NativeMenuItem("Green");

mySubMenu.addItem(subitem1);
mySubMenu.addItem(subitem2);
mySubMenu.addItem(subitem3);

item.submenu = mySubMenu;

subitem1.addEventListener(Event.SELECT, selectItem);
subitem2.addEventListener(Event.SELECT, selectItem);
subitem3.addEventListener(Event.SELECT, selectItem);

function selectItem(evt:Event):void
{
trace("You've pressed the " + evt.target.label);
}

Hotkeys are used as shortcuts for commands, and it is always a good thing to include them in your software.

To set a hotkey for a menu item, use the keyEquivalent property of that menu item and pass it a string value of the key that needs to be pressed.

var subitem1:NativeMenuItem = new NativeMenuItem("Red");
subitem1.keyEquivalent = 'r';

If you test your application now, the "Red" subitem is going to have a "CTRL+R" (Windows) or "Command+R" (Mac OS) next to it. If you close the menu and try hitting CTRL+R, you will get the exact same results that you would get if you selected the item from the menu.

Note that I set the keyEquivalent to "r", not "R", but it still shows up as "R" in the menu. Why? Because if I would set the keyEquivalent to "R", it would set the hotkey to CTRL+SHIFT+R (Windows) or Command + SHIFT + R (Mac OS).

Now, what is this CTRL/Command part, how did it get there? We didn't include any of this stuff in the keyEquivalent, why is this here?

It is because hotkeys consist of a key + modifiers. Modifiers are the additional keys that can be used to create hotkeys that consist of more than 1 key. By default the modifiers is CTRL for Windows and Command for OS X.

You can set your modifiers using the keyEquivalentModifiers property of the menu item:

subitem3.keyEquivalentModifiers = [Keyboard.ALTERNATE];

Valid key modifiers are: Keyboard.ALTERNATE, Keyboard.COMMAND, Keyboard.CONTROL.

That's all for now. Thanks for reading!

Related:

Working with menus in AIR: Part 1
Working with menus in AIR: Part 2
Working with menus in AIR: Part 3
Working with menus in AIR: Part 4
Working with menus in AIR: Part 5

No comments:

Post a Comment