Skip to content

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 “Previous Track” button from a rewind icon to a Genius Shuffle 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 get called for modifier keys. The solution is to use a Timer to detect the Option/Alt key, though it could be adapted to read any of the modifier keys.

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, something I always recommend. Also, the subclass will allow you to call events which can come in handy.

Start by creating a new class called “OptionTimer” whose super is “Timer”. Next, add a property “Pressed As Boolean”, an event definition “KeyDown”, and a second event definition “KeyUp” to OptionTimer. Lastly add the Action event handler with the following code:

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

That’s it for code. Now go to your Window, place a Timer on it and set the super to “OptionTimer” and 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 200 to make sure the events are responsive.

To test this, add a Label to the Window which will be used to display different text when the Option key is held down. In the Timer subclass, put this code in the KeyDown event:

Label1.Value = "You are pressing Option."

And in the KeyUp event put this code:

Label1.Value = "Normal Text"

Run the project and watch the text change when you hold and release the Option/Alt key.

*Updated from an original post written by Thom McGrath.