Keyイベントの登録方法Air(Flex)の画面にてKeyイベントをListenして処理を組み込む場合には、KeyboardEventをaddEventListenerします。addEventListener(KeyboardEvent.KEY_DOWN, KeyboadEventにはKEY_DOWN,KEY_UPがあります。function(e:KeyboardEvent):void { trace(e.keyCode); } } KeyboadEventには、alt,shift,control,commandが押されているかどうかのboolean値と、keycode, charcodeの情報が含まれています。 keycodeの値は、flash.ui.Keyboad にて定数が切られています。(Swingでいう、KeyEvent) これらを使って、ESCAPEキーを押された場合のイベントは以下のように記述が出来ます。 addEventListener(KeyboardEvent.KEY_DOWN, ESCAPEキーが押されたときに画面を閉じる処理などを書く場合には上記のようにKEY_DOWNのタイミングでもいいと思うのですが、Ctrl+ESCAPEのようにModifierを組み合わせた場合には、KEY_DOWNでなく、KEY_UPを使うと良いみたいです。function(e:KeyboardEvent):void { if (e.keyCode == Keyboard.ESCAPE) { trace("Escapeキーが押されました); } } } addEventListener(KeyboardEvent.KEY_UP, ちなみに、上記のコードでKeyboardEvent.KEY_DOWNにすると、keyCodeの値はCtrlキーになってしまいます。function(e:KeyboardEvent):void { if (e.ctrlKey && e.keyCode == Keyboard.ESCAPE) { trace("Ctrl+Escapeキーが押されました); } } } GUIコントロール部品でのKeyListenermx:TextInputなどのGUIコントロール部品にてKeyLitenerを行ないたい場合には、その部品に対してaddEventListenerすればOKです。var text:TextInput; text.addEventListener(KeyboardEvent.KEY_UP, function(e:KeyboardEvent):void { trace(e.keyCode); } } 画面内でのKeyListenermx:WindowedApplicationの場合WindowedApplication#addEventListenerではなぜか反応しませんでした。Stage#addEventListenerだと反応するようなので、以下のようなコードになります。 var window:WindowedApplication; window.stage.addEventListener(KeyboardEvent.KEY_DOWN, function(e:KeyboardEvent):void { trace(e.keyCode); } } mx:Windowの場合WindowedApplication同様、Stageに対してaddEventListenerします。mx:TitleWindowの場合TitleWindow#addEventListenerで反応します。var window:TitleWindow; window.addEventListener(KeyboardEvent.KEY_DOWN, function(e:KeyboardEvent):void { trace(e.keyCode); } } Airアプリケーション全体へのKeyListenerWindowメニューへのショートカットなど、アプリケーション全体としてショートカットKeyを使いたい場合。NativeApplicationに対してaddEventListenerするとOKのようです。 mx:WindowedApplicationからの場合だと、以下のような感じ。 var window:WindowedApplication; window.nativeApplication.addEventListener(KeyboardEvent.KEY_DOWN, function(e:KeyboardEvent):void { trace(e.keyCode); } } 複数EventListenerを登録した場合の順序Stageに対して、複数EventLitener(KeyboadEvent.KEY_DOWN)を登録した場合は、登録された順序で実行されるようです。var window:WindowedApplication; 実行結果window.stage.addEventListener(KeyboardEvent.KEY_DOWN, function(e:KeyboardEvent):void { trace("event1"); } } window.stage.addEventListener(KeyboardEvent.KEY_DOWN, function(e:KeyboardEvent):void { trace("event2"); } } event1 StageとNativeApplicationと両方に登録した場合には、Stageのものが優先的に実行されるようです。event2 var window:WindowedApplication; 実行結果window.nativeApplication.addEventListener(KeyboardEvent.KEY_DOWN, function(e:KeyboardEvent):void { trace("native1"); } } window.stage.addEventListener(KeyboardEvent.KEY_DOWN, function(e:KeyboardEvent):void { trace("stage1"); } } window.nativeApplication.addEventListener(KeyboardEvent.KEY_DOWN, function(e:KeyboardEvent):void { trace("native2"); } } window.stage.addEventListener(KeyboardEvent.KEY_DOWN, function(e:KeyboardEvent):void { trace("stage2"); } } stage1 stage2 native1 native2 |