Wednesday, March 2, 2011

Detecting Modifier Keys

Sometimes it is necessary, or at least user-friendly, to adjust your interface when the user holds down modifier keys. For example, iTunes changes its "Create Playlist" button from a plus icon to a gear icon when the option key is held down. The goal is to inform the user that option-clicking the button will perform a different task.

At first glance you might think that simply looking for the option key in a KeyDown event will do the trick. The problem is KeyDown/KeyUp does not fire for modifier keys. The solution is to use a Timer, which I'll show you how to setup. In this tutorial we'll be creating a timer to detect the option/alt key, though this class could be adapted to read any of the modifiers.

First of all, we need to decide whether to create a timer embedded on a Window, or to create a subclass. Either technique will work, but the subclass creates reusable code which I always recommend. Also, the subclass will allow us to trigger events which will come in handy.

Start by creating a new class called "OptionTimer" whose super is "Timer". Next, add a property "Pressed As Boolean", an event "KeyDown", and a second event "KeyUp" to OptionTimer. In the Action event insert the following code:

If Keyboard.AsyncAltKey = True And Pressed = False Then
Pressed = True
RaiseEvent KeyDown
Else If KeyBoard.AsyncAltKey = False And Pressed = True Then
Pressed = False
RaiseEvent KeyUp
End If

That's it, nothing more the class needs to do. So go to your Window and place a Timer on it. Set the super to "OptionTimer" and now you can insert code into the events for that timer. You'll also want to adjust the period of the timer to something small such as 250 to make sure the events are responsive.

To test it we could use a MsgBox in each event but MsgBoxes are blocking and require user interaction. Since this test is about user interaction, we should avoid the MsgBox. So instead, in the KeyDown event insert a single "Beep" command. And in the KeyUp event insert two "Beep" commands. When you run your project, you should hear a beep when you press the option key and two beeps when you release it.

1 comment:

Unknown said...

Pretty usefull to me, now if i only had the Bottom-bar shown in the image i'd been complete here..;)