Saturday, January 18, 2014

Keyboard Attached Event in WPF

There is one namespaces named System.Windows.Input where keyboard class is defined.
Keyboard class represents the keyboard device which provides keyboard related events, method and properties that provides information about the state of the keyboard.Each of the events that keyboard defines is an attached event.
In order to receive keyboard input, the element must be Focusable.Most UIElement derived objects are Focusable and if not then set the Focusable property on the base element to true.
Some useful events KeyUp, KeyDown, PreviewKeyUp, PreviewKeyDown, GotkeyboardFocus and LostKeyboardFocus are attached events of keyboard class.

KeyUp: This event occurs when a key on the keyboard is released.
KeyDown: This event occurs when a key is pressed on the keyboard.
Preview KeyUp: This is a tunneling event corresponding to KeyUp event.
Preview KeyDown: This is a tunneling event corresponding to KeyDown event.
GotkeyboardFocus: This event occurs when an element receives keyboard focus.
LostkeyboardFocus: This event occurs when an element loses keyboard focus.

KeyboardEventExample1.xaml




KeyboardEventExample1.xaml.cs
















UI Display:
After Pressing F5, GotkeyboardFocus event get fired as shown below when we click in TextBox and hence Text’s Background color get changed to Green.












After losing focus on TextBox, LostkeyboardFocus event get fired when we click or move cursor to other window and Text’s Background color get changed to Red.












Notes:
1.       There can be only one element with keyboard focus on the entire desktop.
2.       Keyboard focus refers to the object that is receiving keyboard input.
3.       For StackPanel and Canvas, the default value of Focusable property is false.

No comments:

Copyright © Codingnodes,2014.All Rights Reserved.