Keyboard and Ink Input with WPF - Keyboard State
(Page 2 of 4 )
The Keyboard class provides a static property called Modifiers. You can read this at any time to find out which modifier keys, such as the Alt, Shift, and Ctrl keys, are pressed. Example 4-12 shows how you might use this in code that needs to decide whether to copy or move an item according to whether the Ctrl key is pressed.
Example 4-12. Reading keyboard modifiers
if (Keyboard.Modifiers & ModifierKeys.Control) != 0) {
isCopy = true;
}
Keyboardalso provides theIsKeyDownandIsKeyUpmethods, which let you query the state of any individual key, as shown in Example 4-13.
Example 4-13. Reading individual key state
bool homeKeyPressed = Keyboard.IsKeyDown(Key.Home);
You can also discover which element has the keyboard focus, using the staticFocusedElementproperty, or set the focus into a particular element by calling theFocusmethod.
The state information returned byKeyboarddoes not represent the current state. It represents a snapshot of the state for the event currently being processed. This means that if for some reason, your application gets bogged down and gets slightly behind in processing messages, the keyboard state will remain consistent.
As an example of why this is important, consider a drag operation where the Ctrl key determines whether the operation is a move or a copy. To behave correctly, your mouse up handler needs to know the state the Ctrl key had when the mouse button was released, rather than the state that it’s in now. If the user releases the Ctrl key after letting go of the mouse button, but before your application has processed the mouse up event, the user will expect a copy operation to be performed, and he will be unhappy if the application performs a move simply because your code couldn’t keep up. By returning a snapshot of the keyboard state rather than its immediate state, theKeyboardclass saves you from this problem.
Next: Ink Input >>
More .NET Articles
More By O'Reilly Media
|
This article is excerpted from Programming WPF, Second Edition, written by Chris Sells and Ian Griffiths (O'Reilly, 2007; ISBN: 0596510373). Check it out today at your favorite bookstore. Buy this book now.
|
|