Friday, August 19, 2011

FileMaker TIP: How To Trap For Modifier Keys

There are times when you want to allow some advanced functionality when a combination of modifier keys (shift, alt, ctrl, etc.) are held down. I've seen some developers go nuts with this - using one button with 5 or 6 functions based on what keys are held down...

OUCH.

I my opinion, not the best way to go - since the user has to "know" to hold down some combination of keys in order to make some functionality work. Instead, the user interface should be easily discoverable - and familiar to use. But I digress...

In FileMaker, you can tell which modifier keys are held down by using the function:
Get ( ActiveModifierKeys )
Here's what you'll get back:
Shift = 1
Caps Lock = 2
Ctrl (Windows) / Control (Mac OS) = 4
Alt (Windows) / Option (Mac OS) = 8
Command (Mac OS) = 16
If all modifier keys are being pressed (on a Mac), the function will return 31 (1+2+4+8+16).

It's no problem if you only want to check for a single key down - you could just use something like this:
If ( Get ( ActiveModifierKeys ) = 1 //Shift is down )
    # Do Some Action
Else
   # Do Some Other Action
End If
It gets a little more interesting when you want to check the combinations of keys - because you would have to trap for all the possible variations (On Windows):
Ctrl + Shift = 5
Ctrl + Alt = 12
Shift + Alt = 9
Shift + Ctrl + Alt = 13
Then if you (or your customer) is on a Mac, you need to add these:
Command + Shift = 17
Command + Option = 24
Command + Control = 20
Command + Control + Shift = 21
Command + Control + Option = 28
Command + Shift + Option = 25
Command + Shift + Option + Control = 29
Like I said, if you, as a developer, are in your right mind - you would NEVER have a customer have to hold down Command + Shift + Option + Control when clicking a button! However, I understand that sometimes "keys happen."

In searching around the interwebs - I found a number of interesting solutions to finding out what key(s) are being held down. There are some great custom functions out there - "KeysDown" by Peter Wagemans over on www.briandunning.com takes natural language-like arguments:
KeysDown ( "shift-ctrl" ; True )
KeysDown ( "ctrl-shift-alt" ; False )
KeysDown ( "ctrl-capslock" ; False )
There's another custom function by Arnold Kegebein on his gallimaufry blog that will create global variables to hold all the key states. You can then use syntax like this in your scripts:

Set Variable [$modifierKeys; Value: get.modifierKeys]
If [$$CTRL;]
   … do something …
ElseIf [$$SHIFT];
   … do something else …
End If
So, whether you use custom functions, create a script, or even a calculation - you'll always know the state of the modifier key!

No comments:

Web Analytics