Flex 3: Key press combination to trigger an event/function
Within a specific canvas, I would like a user to be able to p开发者_如何学Cress a combination of keys which will trigger an event.(a bit like a cheat in an old megadrive game). Not sure where to start though. Anyone know if it is possible and if so could you give me a clue with how to start?
Thanks in advance!
You can add an eventListener to the top level application for the KeyboardEvent.KEY_DOWN
event and check for key combinations there. From this article:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute" creationComplete="init()">
<mx:Script>
<![CDATA[
private function init():void{
this.addEventListener(MouseEvent.CLICK, clickHandler);
this.addEventListener(KeyboardEvent.KEY_DOWN,keyPressed);
}
private function clickHandler(event:MouseEvent):void {
stage.focus = this;
}
private function keyPressed(evt:KeyboardEvent):void{
if(evt.ctrlKey && evt.keyCode == 65)
trace("CTRL A is pressed");
if(evt.ctrlKey && evt.keyCode == 66)
trace("CTRL B is pressed");
}
]]>
</mx:Script>
</mx:Application>
A canvas won't dispatch key up or key down events. You can add a listener to them; as the key events will bubble; but it won't dispatch them alone. Unfortunately, an input component, such as a textInput, needs to have focus for the key press events to dispatch.
Instead of using a canvas, group, or other container, I'd look into using a Spark TextInput with a customized skin that makes it, and the typed text, essentially invisible.
精彩评论