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