Catching keyboard events

The program Key.m3 demonstrates catching keyboard events. The program defines a new VBT that acquires keyboard events whenever the mouse moves into the VBT. If a key is pressed and released while the mouse is in the window and if it is a printable character, then the character is displayed in the window.

We have named the new VBT KeyVBT. It is a subtype of TextVBT.T which itself is a subtype of VBT.T. The type KeyVBT overrides the position and key methods of VBT.T. For convenience we have written an init procedure which hides the init procedure of TextVBT.T. However the init procedure of the superclass does all the work in the line

EVAL TextVBT.T.init (v, t, fnt:=f);
of the program.

Handling the keyboard events requires two main parts. These are accomplished in the procedures Position and Key of program Key. The procedure Position acquires the keyboard focus for the application, if the mouse pointer moves into the application's KeyVBT. Then if a key is pressed in the VBT and this key is a printable character, the subprocedure Key sets the text to the appropriate character.

The situation is depicted in a series of snapshots of the application

The initial text is the string [uninitialized]. After the key ``F'' is pressed in the KeyVBT, the text is changed to character 'F'. After the key ``%'' is pressed, the text is changed to the character '%'.