Keyboard and Mouse Events Handling Keyboard Events Aside
Keyboard and Mouse Events
Handling Keyboard Events • Aside from keyboard shortcuts, there are other ways to handle keyboard activity in your programs. • This can be especially useful in games or other programs which use the keyboard for something besides typing text. • VB Forms, and most other controls, respond to three different keyboard events: • Key. Press • Key. Down • Key. Up
Key. Press • Key. Press happens when the user presses a key or key combination (like Shift+A). • The Key. Press event’s “e” parameter returns a “processed” value from the keyboard. • For instance, if the user types an “A” with the shift key down, e. Key. Char will return “A”, indicating that the user types a capital “A”. If an “A” is typed without the shift key down, e. Key. Char will return “a”. • Similarly the “ 4” key will have e. Key. Char equal to “ 4”, but it will be “$” if the shift key is down.
Key. Down, Key. Up • In contrast, Key. Down and Key. Up return more “raw” information— they tell you exactly what key combinations have been typed. • As the name implies, Key. Down occurs when a key is pushed down, and Key. Up occurs when a key is released. This allows you to respond to each event separately, something you can’t do with Key. Press. • If you had a driving game, you could say “Hold the ‘B’ key to brake, and release it to stop braking. ” • The “e” parameter for Key. Down and Key. Up contains more information: • e. Shift, e. Alt, e. Control are Booleans which indicate which of these keys was pressed when the other key was pushed down or released. • e. Key. Code is an enumeration with a value matching each key on the keyboard, including the function keys, the direction keys, and the numeric keypad keys.
• The “Using the Keyboard and Mouse” program demonstrates the use of these events.
The Code
Key. Preview • An important point: All of these events being handled are Form events. This is the simplest way to handle keyboard input (instead of responding to events from individual controls). • To make this work, you need to set the form’s Key. Preview property to True. • This allows the form’s events to respond before any other control events (such as typing in a Text. Box). • Play with the “Using the Keyboard and Mouse” program to get a feel for how to use the Key. Press, Key. Down, and Key. Up events.
Mouse Events • The previous slide explains how to handle various mouse events in your program. • That form is a part of the “Using the Keyboard and Mouse” program; simply double-click on the “Using the Keyboard” form to bring up the Mouse Events form. • The next slide shows the code for the Mouse Events form. • Again, play with the Mouse Events form to get a feel for how these events work.
Mouse Code
- Slides: 10