#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.

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

  1. Pingback: Dew Drop – September 13, 2012 (#1,400) | Alvin Ashcraft's Morning Dew

  2. Pingback: #649 – KeyStates Property Combines IsDown and IsToggled « 2,000 Things You Should Know About WPF

Leave a comment