Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple Example of Using Keyboard Events from Javascript to Actionscript, so you can hijack Browser Keyboard Handlers
var FlexKeyboardHandler = FlexKeyboardHandler || {}
FlexKeyboardHandler.setup = function ()
{
window.addEventListener("keypress", FlexKeyboardHandler.keydownHandler, true);
window.addEventListener("keydown", FlexKeyboardHandler.keydownHandler, true);
getFlexApplication("MyApp").addEventListener("keypress", FlexKeyboardHandler.keydownHandler, true);
getFlexApplication("MyApp").addEventListener("keypress", FlexKeyboardHandler.keydownHandler, false);
window.focus();
};
var hotKey = null;
FlexKeyboardHandler.keydownHandler = function(event)
{
// without focus, the javascript will recieve special keys
// however, without focus, it won't recieve anything else
// as a workaround, set the focus when the first special key is pressed
window.focus();
var evtobj = window.event ? event : e;
var hotKeyPressed = (evtobj.altKey || evtobj.ctrlKey || evtobj.shiftKey);
// first capture the special key
if (!hotKey && hotKeyPressed)
{
hotKey = evtobj.keyCode;
return;
}
// if it's pressed, then check for the letter
if (hotKeyPressed && event.keyCode != hotKey)
{
// in this hotKeyHandler function, it's a good idea to restore
// the flex application's focus to what it originally was
// before we called window.focus();
getFlexApplication("MyApp").hotKeyHandler(hotKey, event.keyCode);
}
hotKey = null;
};
function getFlexApplication(appName)
{
if (navigator.appName.indexOf ("Microsoft") !=-1)
return window[appName];
else
return document[appName];
}
window.addEventListener("load", FlexKeyboardHandler.setup, false);
<?xml version="1.0" encoding="utf-8"?>
<s:Application
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
viewSourceURL="srcview/index.html"
creationComplete="creationCompleteHandler()">
<fx:Script>
<![CDATA[
protected function creationCompleteHandler():void
{
if (ExternalInterface.available)
{
ExternalInterface.addCallback("hotKeyHandler", hotKeyHandler);
ExternalInterface.addCallback("traceKey", traceKey);
}
}
protected function hotKeyHandler(specialKey:int, letterKey:int):void
{
trace(specialKey, letterKey);
}
protected function traceKey(hotKeyPressed:Boolean):void
{
trace(hotKeyPressed);
}
]]>
</fx:Script>
<s:Group width="100%" height="100%">
<s:Rect width="100%" height="100%">
<s:fill>
<mx:SolidColor color="0xaaaaaa" alpha=".5"/>
</s:fill>
</s:Rect>
</s:Group>
</s:Application>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.