In the next example, you will create a simple Windows application with a single-line Text Box for entering keystrokes. Set the properties of the form and the controls to the values shown in Table 4-8. It takes two arguments: a string which should contain the name of the event and the instance of Key Event Args.A larger multiline Text Box will display the keystroke events and event argument properties so that you can see what is going on. When done, the form should look something like Figure 4-7. The first argument is used in the first line in the method to display which event is being handled.Unicode also allows for character sets containing many more characters than an ASCII character set, such as special symbols and stylings of characters.You can insert Unicode characters or determine the Unicode character code for any character in Windows using the Character Map tool, which is accessible by clicking on the Start menu and then Programs The Key Press event exposes two properties contained in Key Press Event Args, listed in Table 4-7.Add the highlighted lines of code shown in Example 4-6 for C# and in Example 4-7 for VB. Again, remember not to double-click on the txt Input control, since that will implement the default event, which is not what you want here.
The Key Down and Key Press events may seem somewhat redundant, but they fire at different points in the keyboard event stream and contain different information in the Event Args object.
(The ASCII characters are listed in Appendix A.) The cast is done in C# using the cast operator (( )) and in VB. There is another significant difference between the two languages here. The Key Data property returns the same information as the Key Code property combined with flags to indicate which modifier keys were pressed, if any. Add the highlighted code shown in Example 4-14 (for C#) or in Example 4-15 (for VB. This event handler will get the character from the Key Press Event Args event argument, and then append various pieces of information about the character to a string displayed in the txt Msg Text Box.
The C# version embeds tab characters and new lines using escape sequences in string literals, while the VB. In this example, the Shift Key was pressed in combination with the Shift modifier key (that does seem redundant since they are the same key) and the G key was pressed, also in combination with the Shift modifier key. It also populates the lbl Upper label with an uppercase version of the character and lbl Lower label with a lowercase version.
The next example will use keystroke information and the Validating event to control and validate the contents entered into a text box.
It is often useful or necessary to capture keystrokes and then take action based on the details related to that keystroke.