rid
rid

Reputation: 63472

How do I find out if the mouse button is down?

Is there any way to find out at any time if the mouse button is down?

I have some code that runs while the mouse button is down, but if I switch away from the Flash client while the mouse button is down, then the mouse up listeners are never called, so I'd like to account for this situation by checking if the mouse button is still down.

Ideally, I'd like something like:

if (Mouse.isDown) {
    trace("down");
} else {
    trace("up");
}

Upvotes: 0

Views: 2698

Answers (2)

www0z0k
www0z0k

Reputation: 4434

you need to check the MouseEvent::buttonDown property in the MouseEvent.MOUSE_MOVE handler to switch some Boolean flag
upd
code:

package {
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent; 
    /**
     * ...
     * @author www0z0k
     */
    [SWF (width="320", height="240", frameRate="24")]
    public class Main extends Sprite {
        private var _isDown:Boolean = false;
        public function Main():void {
            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE, init);
        }

        private function init(e:Event = null):void {
            removeEventListener(Event.ADDED_TO_STAGE, init);
            color = 0;
            stage.addEventListener(MouseEvent.MOUSE_MOVE, onMove);
        }

        private function onMove(e:MouseEvent):void {
            color = e.buttonDown ? 0xffff00 : 0x0000ff;
        }

        public function set color(value:int):void {
            graphics.clear();
            graphics.beginFill(value);
            graphics.drawRect(0, 0, 320, 240);
            graphics.endFill();
        }       
    }   
}

result - i press the button, move the pointer outside firefox, relese the button, click on the other application window, then alt-tab back to firefox and move the mouse in; at this moment my swf recognizes that mouse button is released

upd 2
it works as supposed in firefox 3.6.10 and as described in the question in firefox 7.0.1

Upvotes: 3

rid
rid

Reputation: 63472

I ended up adding an Event.ACTIVATE listener. Whenever Flash receives focus, I check if the mouse button is considered to be down. Since the mouse button can't be down inside the Flash client before the Flash client receives focus, I can safely assume that it should be up and call the appropriate code.

Upvotes: 2

Related Questions