Page 1 of 1

How to check modifier keys in a more readable way

PostPosted: Thu Jul 24, 2008 10:31 am
by mboegem
Remembering syntax for this kind of actions is not my strongest point.
My solution: create a global method which you can call easy and a boolean in return.

//get the last key modifiers of last user action (shift = 1,ctrl = 2,meta = 4,alt = 8 )

var $key = arguments[0]
var m = application.getLastKeyModifiers();


switch($key)
{
case 'shift' :
var i = 1;
break;

case 'ctrl' :
var i = 2;
break;

case 'meta' :
var i = 4;
break;

case 'alt' :
var i = 8;
break;

default:
var i = 'error';
}


return (m & i) == i;

PostPosted: Mon Jul 28, 2008 8:53 pm
by david
There is an offset difference between mac and PC which you can trap for:

Code: Select all
var   keyPressed = application.getLastKeyModifiers()

if (keyPressed >= 16) { //offset for pc/mac values
   keyPressed -= 16
}
...

PostPosted: Tue Jul 29, 2008 5:51 pm
by SteveInLA
Thanks for this, Marc. Here is a variation that accommodates multiple modifier keys. Pass it a string of mod key names delimited with the | character. It works for just a single mod key too:
Code: Select all
var vKey = arguments[ 0 ];
var vKeyArray = vKey.split( "|" );
var m = application.getLastKeyModifiers();
var i = 0;

if ( plugins.it2be_tools.arrayContains( vKeyArray, "shift" ) )
{
   i += 1;
}

if ( plugins.it2be_tools.arrayContains( vKeyArray, "ctrl" ) )
{
   i += 2;
}

if ( plugins.it2be_tools.arrayContains( vKeyArray, "meta" ) )
{
   i += 4;
}

if ( plugins.it2be_tools.arrayContains( vKeyArray, "alt" ) )
{
   i += 8;
}

if ( i == 0 )
{
   i = "error";
}

//offset for pc/mac values
if ( m >= 16 )
{
   m -= 16;
}

return ( m & i ) == i;

Steve in LA

PostPosted: Tue Jul 29, 2008 7:50 pm
by SteveInLA
Oops. My method doesn't exactly work for multiple keys if you evaluate with a bitwise operator. It will work if you use:
Code: Select all
return m == i;

instead of
Code: Select all
return (m & i) == i;

If I only want to return a true value in the case when a single key is pressed and not a combination of keys that include the single key, is there any reason why a bitwise operator is needed?

Steve in LA