#651 – Using Static Members of the Keyboard Class

The KeyboardDevice class represents the current state of the keyboard and is accessible from within keypress event handlers using the KeyEventArgs.KeyboardDevice property.

        private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            Console.WriteLine(string.Format("A key pressed? {0}", e.KeyboardDevice.IsKeyDown(Key.A)));
        }

You can also use the Keyboard.PrimaryDevice property to access the current KeyboardDevice object.

        public void CheckForA()
        {
            Console.WriteLine(string.Format("A key pressed? {0}", Keyboard.PrimaryDevice.IsKeyDown(Key.A)));
        }

In addition to providing access to the KeyboardDevice object, the Keyboard class also provides several static methods that give you the same information.  This is easier than referencing the PrimaryDevice property.

        public void CheckForA()
        {
            Console.WriteLine(string.Format("A key pressed? {0}", Keyboard.IsKeyDown(Key.A)));
        }
Advertisement

#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)));
        }

#648 – Check the Toggled State of Any Key

You can use the KeyboardDevice.IsKeyToggled method to check the toggled state of any of the three toggle keys–Caps Lock, Scroll Lock, or Num Lock.

For example, we can do this in a keypress event handler for a TextBox.

        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)));
        }

Now, as we type, we’re told of the current state of these three toggle keys.