Multi Key Detection

A project I was recently assigned for a company requires that the application detect specific key presses. I took the opportunity to write a very simple Multi Key class, this has suited my needs so far. I’m currently in the process of updating some minor glitches, but I feel that this is something many people could enjoy. Take Care.


class MultiKey {
    
    // code list
    private var codeList : Array;
    
    // the objects listening for events from this object
    private var listeners : Array;
    
    public function MultiKey( keyCodes : Array )
    {
        Key.addListener(this);
        codeList = keyCodes;
        
        listeners = new Array();
    }
    
    
    
    private function onKeyDown() : Void
    {
        for (var i:Number=0; i<codeList.length; i++)
        {
            if (!Key.isDown(codeList*)) {
                return;
            }
        }
        invokeOnKeyCombination();
    }
    //////////////////
    /* BROADCASTING SPECIFIC */
    //////////////////
    private function invokeOnKeyCombination()
    {
        for (var i:Number = 0; i<listeners.length; i++)
        {
            listeners*.onKeyCombination();
        }
    }
    // adds a listener if it is not already in the list
    public function addListener( o : Object ) : Boolean
    {
        // cannot add a null value
        if (o == null) return false;
        
        for (var i:Number = 0; i<listeners.length; i++)
        {
            if (o == listeners*) return false;
        }
        
        // object does not in exist in array
        listeners.push(o);
        return true;
    }
    // removes a listener if it exists in the list
    public function removeListener( o : Object ) : Boolean
    {
        // cannot remove a null value
        if (o == null) return false;
        
        for (var i:Number = 0; i<listeners.length; i++)
        {
            if (o == listeners*)
            {
                listeners.splice(i, 1);
                return true;
            }
        }
        
        // object does not exist in array
        return false;
    }
}

IMPLEMENTATION IN FLA

detects if you press CTRL and SHIFT at the same time.


var mk = new MultiKey([17, 32]);
mk.addListener(this);
function onKeyCombination() {
    trace("Combination Pressed");
}

This sample suited MY needs, but like I said I’m working out some kinks. Take Care.

-Michael