Keyboard State

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;

Keyboard also provides the IsKeyDown and IsKeyUp methods, 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 static FocusedElement property, or set the focus into a particular element by calling the Focus method.

The state information returned by Keyboard does 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, the Keyboard class saves you from this problem.

Was this article helpful?

0 0
Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook


Post a comment