December 7th, 2007 by Kyle
Tags: events, Flex, focus, lose-focus, mouse-event, mouseevent
Posted in: Flex
I have seen a few people and had a customer ask how to detect when a flex app loses focus.
Here is a sample app that shows the technique and a practical application of this functionality.
When you click and drag a DividedBox separator, if you move the mouse outside the Flex application window, the app should realize this and “drop” the separator at that horizontal or vertical position (depending on the orientation of your divider). It doesn’t do this automatically (and maybe is should), but it is easily done and demonstrates the technique that can be used for other reasons.
Here is the simple app:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="addListeners(event)">
<mx:Script>
<![CDATA[
private var lastX:Number;
private var lastY:Number;
private function addListeners(event:Event):void{
systemManager.stage.addEventListener(Event.MOUSE_LEAVE, mouseLeave);
systemManager.stage.addEventListener(Event.DEACTIVATE,deactivate);
systemManager.stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMove);
}
private function removeListeners(event:Event):void{
systemManager.stage.removeEventListener(Event.MOUSE_LEAVE, mouseLeave);
systemManager.stage.removeEventListener(flash.events.Event.DEACTIVATE,deactivate);
systemManager.stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMove);
}
private function mouseMove(event:MouseEvent):void{
//trace("move…");
lastX=event.stageX;
lastY=event.stageY;
}
private function mouseLeave(event:Event):void{
//trace("left");
removeListeners(event);
dispatchEvent(new MouseEvent(MouseEvent.MOUSE_UP,true,false,lastX,lastY));
}
private function deactivate(event:Event):void{
//trace("deactivate");
removeListeners(event);
dispatchEvent(new MouseEvent(MouseEvent.MOUSE_UP,true,false,lastX,lastY));
}
]]>
</mx:Script>
<mx:VDividedBox id="div1" dividerPress="addListeners(event)" dividerRelease="removeListeners(event)">
<mx:VBox height="200" width="300" borderStyle="outset">
<mx:Button label="Something"/>
</mx:VBox>
<mx:VBox height="200" width="300" borderStyle="outset">
<mx:TextArea width="100%"/>
</mx:VBox >
</mx:VDividedBox>
</mx:Application>
Browse the source of this example.
Download a zipfile containing the source to this sample.


April 22nd, 2008 at 3:45 am
Thanks for this solution!
When a user scrolled a list and moved outside the stage and released the mouse, my application never received the MOUSE_UP event. Because of this a drag event was activated in my list itemrenderer when the user entered the stage again. But thanks to your solution this bug is fixed now!