Watching the keyboard
This example illustrates an important point. The PreviewKeyDown and KeyDown events
fire every time a key is pressed. However, the TextInput event only fires when a character is
???typed??? into an element. This action may actually involve multiple key presses. In the example
in Figure 6-5, two key presses are needed to create the capital letter S. First, the Shift key is
pressed, followed by the S key. As a result, you??™ll see two KeyDown and KeyUp events, but only
one TextInput event.
The PreviewKeyDown, KeyDown, PreviewKey, and KeyUp events all provide the same
information through the KeyEventArgs object. The most important detail is the Key property,
which returns a value from the System.Windows.Input.Key enumeration that identifies the
key that was pressed or released. Here??™s the event handler that handles key events for the
example in Figure 6-6:
Private Sub KeyEvent(ByVal sender As Object, ByVal e As KeyEventArgs)
Dim message As String = "Event: " & e.RoutedEvent.ToString() & _
" " & " Key: " & e.Key
lstMessages.Items.Add(message)
End Sub
The Key value doesn??™t take into account the state of any other keys. For example, it doesn??™t
matter whether the Shift key is currently pressed when you press the S key; either way you??™ll
get the same Key value (Key.
Pages:
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338