Flexcomps’s Weblog

Capturing keyboard events in Flex

Posted by: Yogesh Puri on: June 2, 2008

This is a small code in flex /AS3 to demonstrate how you can capture the keyboard events in Flex. The application invokes init() method once the creation of form is completed.

The init() method have two lines of code. The first line is for making sure that once the user click on stage the focus should go onto the application (NOTE: you can modify it to a particular object based incase you want to enable key trapping once an object is selected). Next line adds the listener to keyEvents so once the keyboardEvent triggers the “keyPressed()” method will be invoked.

The functionality of keyPressed method is to check which key is pressed. Here I am trapping a combination of control (CTRL) and “A” or “B” key. There keyboardevents provides you information about if any special key i.e. CTRL / SHIFT is pressed along with another keys. So it makes easy to capture the combination of key.

Note: There is an important aspect you need to take care of while going with keyboard combinations. The operating system and the web browser will process keyboard events before Adobe Flash Player or AIR. For example, in Microsoft Internet Explorer, pressing Ctrl+B the browser window will open the bookmark window before any contained SWF file dispatches a keyboard event. So in this case you may not find the desired behavior. To overcome this you can use javascript as an option or use a different combination of keys.

Here is the test code.

<?xml version="1.0" encoding="utf-8"?>
<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>


20 Responses to "Capturing keyboard events in Flex"

Excellent Tutorial. Thanks

THANK YOU

hi,

This is a good sample but i am facing one problem.

When i click a textbox in that its always focusing the mainpage. so i cannot able to enter username in my textbox.

Can u please solve my problem please.

Hi Raaz

Can you share more details?

Hi,

I am new to flex and started implementing small application here my requierement is to disable Alt and Cntrl and Print Screen button from the keyboard.

Is it possible in flex?

You need to use Javascript in this case. You can not directly override browser controls from Flex or Flash.

Yogesh, could you please give some example for using Javascript in flex application.

Yogesh,

Actually I am running this MXML as individual not in any window application like not in IE.

Working on simple MXML file.

Thanks for this!

Cheers.

Hi,
I am simply trying an example given on live docs

<![CDATA[
import mx.collections.ArrayCollection;
import flash.events.KeyboardEvent;
import mx.charts.events.ChartItemEvent;
[Bindable]
private var expensesAC:ArrayCollection = new ArrayCollection( [
{ Month: "Jan", Profit: 2000, Expenses: 1500, Amount: 450 },
{ Month: "Feb", Profit: 1000, Expenses: 200, Amount: 600 },
{ Month: "Mar", Profit: 1500, Expenses: 500, Amount: 300 },
{ Month: "Apr", Profit: 1800, Expenses: 1200, Amount: 900 },
{ Month: "May", Profit: 2400, Expenses: 575, Amount: 500 } ]);
private function initApp():void {
application.addEventListener(KeyboardEvent.KEY_UP, keyHandler);
}
private function keyHandler(event:KeyboardEvent):void {
var ctrlPressed:Boolean = event.ctrlKey;
// If the user presses Ctrl + A, select all chart items.
if (ctrlPressed) {
var curKeyCode:int = event.keyCode;
if (curKeyCode == 65) { // 65 is the keycode value for ‘a’
selectItems();
}
}
}
private function selectItems():void {
// Create an array of all the chart’s series.
var allSeries:Array = myChart.series;
// Iterate over each series.
for (var i:int=0; i<allSeries.length; i++) {
var selectedData:Array = [];
// Iterate over the number of items in the series.
for (var j:int=0; j

but I am not able to capture key board event .
can you please help me in that?

Thanks and Regards
ms

Hi Monika

Your code is fine. Just add the following line in the initApp() method

focusManager.setFocus(myChart);

This will let the focus be on the charting component, or you need to click and take the focus to the chart component here.

Hope it works for you!

Cheers!

Hi,
I’m trying to capture a ctrl+tab and it’s not working. I’m doing just as you said:

function keyHandler(event:KeyboardEvent):void {
if ((event.ctrlKey) && (event.keyCode == Keyboard.TAB)) {

I’ve tried to use directly ‘9′ instead of Keyboard.TAB and it doesn’t work too.

Do you know if TAB has to be treated differently from the other keys (like ‘A’)?

thanks!

Hi,
I am using Flex 3. through out the application I am using some grids. I am trying to make use of ctrl+F keys to find some keyword in grid same like other files.
Is it possible? If yes how. Please help me.
Thank you all.
Swapnil

hi,
i have a quiz application developed in flex which is shown in a html page in fullscreen mode.Can any body tell me how to disable the refresh button of keyboard?
I have a javascript function in the page which diables this.
it works fine when the focus is on the page but when i click on the flex application and i press F5 the page refreshes .Is there any way to handle this

Hi,

I’m trying to stop users enter invalid keys in a filename box (so none of the disallowed keys like ?/\[] etc etc) on an MXML page in a Flex 3 web app.

I’ve hunted high and low and can’t find any way to ignore unwanted or invalid keystrokes in a TextField or TextInput control…. there seems to be no way (like there is in .Net) to simply ignore the keystroke if it’s invalid.

I just want to have something like this:

private function keyPressed(event:KeyboardEvent):Boolean
{
private var invalidChars:String = “?[]/\=+:;’,*”;
var char:String = String.fromCharCode(event.charCode);
if (invalidChars.indexOf(char,0) >= 0)
{
//CANCEL EVENT HERE SO CHAR DOES NOT SHOW IN TEXTFIELD – BUT HOW?!?!
}
}

I hope someone can put me out of my misery – compared to .net I find AS3 and flex extremely obscure – like there’s a cancelable property but it’s read only… whats the point of that?!

have you tried the “Restrict” attribute for TextInput.

Mike, event.preventDefault() should do it

hi,

how to capture keyboard event in full screen mode ?

thx

hi all,

Can anyone please tell me how to capture the ctrl+z in flex,

i have tried
if(event.keyCode == 90 && event.ctrlKey){ ….}

but this doesnt seem to work in IE :-S

Leave a Reply

 

June 2008
M T W T F S S
« May   Jul »
 1
2345678
9101112131415
16171819202122
23242526272829
30  

Blog Stats

  • 131,528 hits