Flash AS3 Context Menu : How to customize the right-click menu of your flash application

What is the Flash Context Menu?

The Flash Context Menu is the menu that appears when you right-click on a flash swf. This menu normally contains settings, about, zoom and quality if not modified by the user.  This menu is an excellent place to put the copyright or credits of the application with links to author’s own website. If you built it why not put your name on it?

Modify the Context Menu

To modify the Context Menu you must first import a couple classes into your application ContextMenu, ContextMenuItem, and ContextMenuEvent:

import flash.ui.ContextMenu;
import flash.ui.ContextMenuItem;
import flash.events.ContextMenuEvent;

Now lets go ahead and create a new Context Menu

var myMenu:ContextMenu = new ContextMenu();

After creating the context menu i prefer to hide the default options for zoom and quality utilizing the hideBuiltInItems method

myMenu.hideBuiltInItems();

Now to create our custom options. This is done by instantiating new ContextMenuItems and adding them to the custom items list of the ContextMenu. So for example lets create a new menu item with the text “copyright 2009 MDBitz”.

var webMenuItem:ContextMenuItem = new ContextMenuItem("copyright 2009 MDBitz");

To add the item to our custom menu we push it to the customItems array of the menu

myMenu.customItems.push( webMenuItem );

At this point we have created our new menu item but we have not added any event handlers for if a user selects the option. To listen for the event we add a handler for the MENU_ITEM_SELECT event.

webMenuItem.addEventListener( ContextMenuEvent.MENU_ITEM_SELECT, onWebClick );

In the previous step we have set the onWebClick function to be called when the menu item is selected. In this case we are going to open my website in a new window. to do this we are going to use the URLRequest and navigateToURL classes. Again to use these we will first need to import them.

import flash.net.navigateToURL;
import flash.net.URLRequest;

Then we simply create the new request and use the navigateToURL class to go to that website in a new window.

public function onWebClick( event:ContextMenuEvent )
  {
    var url:String = "http://www.mdbitz.com";
    var request:URLRequest = new URLRequest(url);
    navigateToURL(request, '_blank');
}

Finally we are ready to set this menu as the context menu for the flash application. This is done by setting the contextMenu to our menu.

this.contextMenu = myMenu;

You know have your own customized context menu. An important item to remember though is that you can only have a limit of 15 items in the custom menu.

Resources

// Flash //

Comments & Questions

Add Your Comment