Using the Keyboard Object


From a user’s perspective, the Keyboard object represents the entire keyboard. Just as the System object is the only instance of the CSystem class, the Keyboard object is the only instance of the CKeyboard class. PublicNotCreatable instancing ensures that you can’t create a false model of your computer with an array of 20 keyboards.


The CKeyboard class, shown in Figure 9-7, has properties that allow you to read or modify the state of any key. Of course, most users are interested only in the state of the toggle keys Caps Lock, Insert, Num Lock, and Scroll Lock. Therefore, CKeyboard provides properties that offer easy access to these keys: Caps­State, InsState, NumState, and ScrollState.



Figure 9-7. The CKeyboard class.


Let’s look at how Edwina handles the Caps Lock key with the CapsState property. There are two parts of this problem: the Caps display and the actual Caps state. The status bar handles the display automatically. You just assign a status panel of type Caps by assigning sbrCaps to the Style property. The panel will automatically display the text CAPS in black (if the CAPS state is on), or in disabled gray (if the CAPS state is off). Unfortunately, it works only one way. You can’t change the CAPS state by changing the Enabled property of the panel as you could with the Key State control. But you can turn off the CAPS state with the Keyboard object. Here’s how it’s done in the Select Case block that handles the status bar panels:

keyboard.CapsState = Not keyboard.CapsState

You don’t need to do anything to make the panel display update to show the correct state. I imagine there must be a timer in the StatusBar control that periodically checks the current state.


You could add ScrollLock, NumLock, and Insert panels that work the same way. Unfortunately, such an Insert panel would show the global insert state correctly, but it wouldn’t show Edwina’s true insert state.