#646 – Detecting a Key’s Toggle State in a Keypress Handler

There are several keys on the keyboard that typically act as toggles–when you first press the key, it is considered toggled, or on–and when you press it again, it is considered untoggled, or off.

The keys that are typically used as toggle keys are: Caps Lock, Scroll Lock and Num Lock.  (Note–the normal Shift key is not typically used as a toggle key).

When a key is pressed, you can determine whether it is entering the toggled state or the untoggled state by checking the KeyEventArgs.IsToggled property in one of the keypress event handlers.

        private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
            Trace.WriteLine(string.Format("----- PreviewKeyDown for key {0}, toggled = {1}", e.Key, e.IsToggled));

For example, if I press the Caps Lock four times, I’ll see the following output:

The Caps Lock key is toggling on and off.