WPF captures keyboard input events and wpf captures keyboard input
A recently modified requirement requires that the Text entered by the keyboard be captured, including various punctuations.
First, we thought of Keyboard Events such as PreviewKeyDown or PreviewKeyUp.
However, the KeyEventArgs objects of these two events are not enough. The KeyEventArgs depends on the Key to determine what the input is, and then writes the Text of the corresponding Key to obtain the data.
For example, Shift + 8 is required for the combination Key to obtain the multiplication Key (the multiplication Key of the numeric keypad is Key. Multiply, and the combination Key is required for the acquisition of the primary and keyboard spaces)
1 private void Window_PreviewKeyDown(object sender, KeyEventArgs e)2 {3 if(e.KeyStates == Keyboard.GetKeyStates(Key.D8) && Keyboard.Modifiers == ModifierKeys.Shift)4 {5 var input = "*";6 }7 }
This method is unfriendly and requires additional if conditions when other punctuation marks are used, and Key conflicts may occur, after you enter the multiplication Key, you may add an "8" value because of the Key. d8 causes
Later, I spent some time searching for a foreign blog and found this article (reference 1). In fact, the solution blog in this article can also find several articles, but they are not detailed.
This is the code I wrote in the article.
XAML:
1 <Window x:Class="Dome.MainWindow"2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"4 PreviewTextInput="Window_PreviewTextInput"5 Height="400" 6 Width="600"7 MinWidth="600">8 </Window>
C #:
1 private void Window_PreviewTextInput(object sender, TextCompositionEventArgs e)2 {3 var input = e.Text;4 }
Reference
Http://stackoverflow.com/questions/2924928/wpf-previewkeydown-event-and-underscore-char
Summary
There are also many related articles on the differences between PreviewKeyDown and KeyDown. I will write one in the future. After all, I have encountered this pitfall...