#650 – Getting Information About Keyboard Keys from Any Method

You can use the KeyEventArgs.KeyboardDevice property within a keypress handler to get information about any keyboard key.  For example:

private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
    Console.WriteLine(string.Format("Toggle info: Caps Lock:{0}, Scroll Lock: {1}, Num Lock: {2}",
        e.KeyboardDevice.IsKeyToggled(Key.CapsLock),
        e.KeyboardDevice.IsKeyToggled(Key.Scroll),
        e.KeyboardDevice.IsKeyToggled(Key.NumLock)));
}

You can also access the same KeyboardDevice object from any method, using the Keyboard.PrimaryDevice property (found in System.Windows.Input). This property will refer to an instance of a KeyboardDevice object.

        public void MyFunctionToGetKeyInfo()
        {
            Console.WriteLine(string.Format("Toggle info: Caps Lock:{0}, Scroll Lock: {1}, Num Lock: {2}",
                Keyboard.PrimaryDevice.IsKeyToggled(Key.CapsLock),
                Keyboard.PrimaryDevice.IsKeyToggled(Key.Scroll),
                Keyboard.PrimaryDevice.IsKeyToggled(Key.NumLock)));
        }
Advertisement

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

One Response to #650 – Getting Information About Keyboard Keys from Any Method

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: