# Keyboard routines

- clear_keybuf — Clears the keyboard buffer.
- install_keyboard — Installs the Allegro keyboard interrupt handler.
- install_keyboard_hooks — Installs custom keyboard hooks.
- key — Array of flags indicating key state.
- key_led_flag — Flag to prevent the keyboard LEDs from being updated.
- key_shifts — Bitmask containing the current state of modifier keys.
- keyboard_callback — User specified keyboard callback handler.
- keyboard_lowlevel_callback — User specified low level keyboard event handler.
- keyboard_needs_poll — Tells if the keyboard needs polling.
- keyboard_ucallback — User specified unicode keyboard callback handler.
- keypressed — Tells if there are keypresses waiting in the input buffer.
- poll_keyboard — Polls the keyboard.
- readkey — Returns the next character from the keyboard buffer.
- remove_keyboard — Removes the Allegro keyboard handler.
- scancode_to_ascii — Converts a scancode to an ASCII character.
- scancode_to_name — Converts a scancode to a key name.
- set_keyboard_rate — Sets the keyboard repeat rate.
- set_leds — Sets the state of the keyboard LED indicators.
- simulate_keypress — Stuffs a key into the keyboard buffer.
- simulate_ukeypress — Stuffs an unicode key into the keyboard buffer.
- three_finger_flag — Flag to desactivate the emergency exit key combination.
- ureadkey — Returns the next unicode character from the keyboard buffer.

The Allegro keyboard handler provides both buffered input and a set of flags storing the current state of each key. Note that it is not possible to correctly detect every combination of keys, due to the design of the PC keyboard. Up to two or three keys at a time will work fine, but if you press more than that the extras are likely to be ignored (exactly which combinations are possible seems to vary from one keyboard to another).

On DOS, Allegro requires the user to specify the language of the keyboard mapping because it is impossible to obtain this information from the OS, otherwise the default US keyboard mapping will be used. Allegro comes with a prepackaged ``keyboard.dat'` file which you can put along with your binary. If this file is present, Allegro will be able to extract the keyboard mapping information stored there. However, the end user still needs to select which keyboard mapping to use. This can be acomplished through the keyboard variable of the system section in a standard ``allegro.cfg'` configuration file. Read chapter "Configuration routines" for more information about this.

int install_keyboard();
Installs the Allegro keyboard interrupt handler. You must call this before using any of the keyboard input routines. Once you have set up the Allegro handler, you can no longer use operating system calls or C library functions to access the keyboard.

Note that on some platforms the keyboard won't work unless you have set a graphics mode, even if this function returns a success value before calling set_gfx_mode. This can happen in environments with graphic windowed modes, since Allegro usually reads the keyboard through the graphical window (which appears after the set_gfx_mode call). Example:

>           allegro_init();
>           install_timer();
>           install_keyboard();
>           /* We are not 100% sure we can read the keyboard yet! */
>           if (set_gfx_mode(GFX_AUTODETECT, 640, 480, 0, 0) != 0)
>              abort_on_error("Couldn't set graphic mode!")

>           /* Now we are guaranteed to be able to read the keyboard. */
>           readkey();

Return value: Returns zero on success, or a negative number on failure (but you may decide not to check the return value as this function is very unlikely to fail).

> See also: remove_keyboard, poll_keyboard, key, keypressed, readkey, ureadkey, keyboard_callback, keyboard_ucallback, keyboard_lowlevel_callback, three_finger_flag, key_led_flag, set_leds, set_keyboard_rate, set_gfx_mode, Standard config variables.

> Examples using this: Available Allegro examples.

void remove_keyboard();
Removes the keyboard handler, returning control to the operating system. You don't normally need to bother calling this, because allegro_exit() will do it for you. However, you might want to call this during runtime if you want to change the keyboard mapping on those platforms were keyboard mappings are needed. You would first modify the configuration variable holding the keyboard mapping and then reinstall the keyboard handler. Example:

>           remove_keyboard();
>           /* Switch to Spanish keyboard mapping. */
>           set_config_string("system", "keyboard", "es");
>           install_keyboard();

> See also: install_keyboard, allegro_exit, set_config_string.

void install_keyboard_hooks(int (*keypressed)(), int (*readkey)());
You should only use this function if you *aren't* using the rest of the keyboard handler. It should be called in the place of install_keyboard(), and lets you provide callback routines to detect and read keypresses, which will be used by the main keypressed() and readkey() functions. This can be useful if you want to use Allegro's GUI code with a custom keyboard handler, as it provides a way for the GUI to get keyboard input from your own code, bypassing the normal Allegro input system.

> See also: install_keyboard, keypressed, readkey.

int poll_keyboard();
Wherever possible, Allegro will read the keyboard input asynchronously (ie. from inside an interrupt handler), but on some platforms that may not be possible, in which case you must call this routine at regular intervals to update the keyboard state variables.

To help you test your keyboard polling code even if you are programming on a platform that doesn't require it, after the first time that you call this function Allegro will switch into polling mode, so from that point onwards you will have to call this routine in order to get any keyboard input at all, regardless of whether the current driver actually needs to be polled or not.

The keypressed(), readkey(), and ureadkey() functions call poll_keyboard() automatically, so you only need to use this function when accessing the key[] array and key_shifts variable.

Return value: Returns zero on success, or a negative number on failure (ie. no keyboard driver installed).

> See also: keyboard_needs_poll, install_keyboard, key, key_shifts.

> Examples using this: excamera, exsample, exstars.

int keyboard_needs_poll();
Returns TRUE if the current keyboard driver is operating in polling mode.

> See also: poll_keyboard, install_keyboard, key.

extern volatile char key[KEY_MAX];
Array of flags indicating the state of each key, ordered by scancode. Wherever possible these values will be updated asynchronously, but if keyboard_needs_poll() returns TRUE, you must manually call poll_keyboard() to update them with the current input state. The scancodes are defined in allegro/keyboard.h as a series of KEY_* constants (and are also listed below). For example, you could write:

>           if (key[KEY_SPACE])
>              printf("Space is pressed\n");

Note that the array is supposed to represent which keys are physically held down and which keys are not, so it is semantically read-only.

These are the keyboard scancodes:

>           KEY_A ... KEY_Z,
>           KEY_0 ... KEY_9,
>           KEY_0_PAD ... KEY_9_PAD,
>           KEY_F1 ... KEY_F12,

>           KEY_ESC, KEY_TILDE, KEY_MINUS, KEY_EQUALS,
>           KEY_BACKSPACE, KEY_TAB, KEY_OPENBRACE, KEY_CLOSEBRACE,
>           KEY_ENTER, KEY_COLON, KEY_QUOTE, KEY_BACKSLASH,
>           KEY_BACKSLASH2, KEY_COMMA, KEY_STOP, KEY_SLASH,
>           KEY_SPACE,

>           KEY_INSERT, KEY_DEL, KEY_HOME, KEY_END, KEY_PGUP,
>           KEY_PGDN, KEY_LEFT, KEY_RIGHT, KEY_UP, KEY_DOWN,

>           KEY_SLASH_PAD, KEY_ASTERISK, KEY_MINUS_PAD,
>           KEY_PLUS_PAD, KEY_DEL_PAD, KEY_ENTER_PAD,

>           KEY_PRTSCR, KEY_PAUSE,

>           KEY_ABNT_C1, KEY_YEN, KEY_KANA, KEY_CONVERT, KEY_NOCONVERT,
>           KEY_AT, KEY_CIRCUMFLEX, KEY_COLON2, KEY_KANJI,

>           KEY_LSHIFT, KEY_RSHIFT,
>           KEY_LCONTROL, KEY_RCONTROL,
>           KEY_ALT, KEY_ALTGR,
>           KEY_LWIN, KEY_RWIN, KEY_MENU,
>           KEY_SCRLOCK, KEY_NUMLOCK, KEY_CAPSLOCK

>           KEY_EQUALS_PAD, KEY_BACKQUOTE, KEY_SEMICOLON, KEY_COMMAND

Finally, you may notice an ``odd'` behaviour of the KEY_PAUSE key. This key only generates an interrupt when it is pressed, not when it is released. For this reason, Allegro pretends the pause key is a ``state'` key, which is the only way to make it usable.

> See also: install_keyboard, poll_keyboard, key_shifts.

> Examples using this: Available Allegro examples.

extern volatile int key_shifts;
Bitmask containing the current state of shift/ctrl/alt, the special Windows keys, and the accent escape characters. Wherever possible this value will be updated asynchronously, but if keyboard_needs_poll() returns TRUE, you must manually call poll_keyboard() to update it with the current input state. This can contain any of the flags:

>           KB_SHIFT_FLAG
>           KB_CTRL_FLAG
>           KB_ALT_FLAG
>           KB_LWIN_FLAG
>           KB_RWIN_FLAG
>           KB_MENU_FLAG
>           KB_COMMAND_FLAG
>           KB_SCROLOCK_FLAG
>           KB_NUMLOCK_FLAG
>           KB_CAPSLOCK_FLAG
>           KB_INALTSEQ_FLAG
>           KB_ACCENT1_FLAG
>           KB_ACCENT2_FLAG
>           KB_ACCENT3_FLAG
>           KB_ACCENT4_FLAG

Example:

>           if (key[KEY_W]) {
>              if (key_shifts & KB_SHIFT_FLAG) {
>                 /* User is pressing shift + W. */
>              } else {
>                 /* Hmmm... lower case W then. */
>              }
>           }

> See also: install_keyboard, poll_keyboard, key.

> Examples using this: excamera, exkeys.

int keypressed();
Returns TRUE if there are keypresses waiting in the input buffer. You can use this to see if the next call to readkey() is going to block or to simply wait for the user to press a key while you still update the screen possibly drawing some animation. Example:

>           while (!keypressed()) {
>              /* Show cool animated logo. */
>           }
>           /* So he skipped our title screen. */

> See also: install_keyboard, readkey, ureadkey, clear_keybuf, simulate_keypress, simulate_ukeypress.

> Examples using this: Available Allegro examples.

int readkey();
Returns the next character from the keyboard buffer, in ASCII format. If the buffer is empty, it waits until a key is pressed. You can see if there are queued keypresses with keypressed().

The low byte of the return value contains the ASCII code of the key, and the high byte the scancode. The scancode remains the same whatever the state of the shift, ctrl and alt keys, while the ASCII code is affected by shift and ctrl in the normal way (shift changes case, ctrl+letter gives the position of that letter in the alphabet, eg. ctrl+A = 1, ctrl+B = 2, etc). Pressing alt+key returns only the scancode, with a zero ASCII code in the low byte. For example:

>           int val;
>           ...
>           val = readkey();
>           if ((val & 0xff) == 'd')     /* by ASCII code */
>              allegro_message("You pressed 'd'\n");

>           if ((val >> 8) == KEY_SPACE) /* by scancode */
>              allegro_message("You pressed Space\n");

>           if ((val & 0xff) == 3)       /* ctrl+letter */
>              allegro_message("You pressed Control+C\n");

>           if (val == (KEY_X << 8))     /* alt+letter */
>              allegro_message("You pressed Alt+X\n");

This function cannot return character values greater than 255. If you need to read Unicode input, use ureadkey() instead.

> See also: install_keyboard, ureadkey, keypressed, clear_keybuf, simulate_keypress.

> Examples using this: Available Allegro examples.

int ureadkey(int *scancode);
Returns the next character from the keyboard buffer, in Unicode format. If the buffer is empty, it waits until a key is pressed. You can see if there are queued keypresses with keypressed(). The return value contains the Unicode value of the key, and if not NULL, the pointer argument will be set to the scancode. Unlike readkey(), this function is able to return character values greater than 255. Example:

>           int val, scancode;
>           ...
>           val = ureadkey(&scancode);
>           if (val == 0x00F1)
>              allegro_message("You pressed n with tilde\n");

>           if (val == 0x00DF)
>              allegro_message("You pressed sharp s\n");

You should be able to find Unicode character maps at http://www.unicode.org/. Remember that on DOS you must specify a custom keyboard map (like those found in ``keyboard.dat'`) usually with the help of a configuration file specifying the language mapping (keyboard variable in system section of ``allegro.cfg'`), or you will get the default US keyboard mapping.

> See also: install_keyboard, readkey, keypressed, clear_keybuf, simulate_ukeypress.

> Examples using this: exkeys.

int scancode_to_ascii(int scancode);
Converts the given scancode to an ASCII character for that key (mangling Unicode values), returning the unshifted uncapslocked result of pressing the key, or zero if the key isn't a character-generating key or the lookup can't be done. The lookup cannot be done for keys like the F1-F12 keys or the cursor keys, and some drivers will only return approximate values. Generally, if you want to display the name of a key to the user, you should use the scancode_to_name function.

Example:

>           int ascii;
>           ...
>           ascii = scancode_to_ascii(scancode);
>           allegro_message("You pressed '%c'\n", ascii);

> See also: scancode_to_name.

const char *scancode_to_name(int scancode);
This function returns a string pointer containing the name of they key with the given scancode. This is useful if you e.g. let the user choose a key for some action, and want to display something more meaningful than just the scancode. Example:

>           char const *keyname = scancode_to_name(scancode);
>           allegro_message("You pressed the %s key.", keyname);

> See also: scancode_to_ascii.

> Examples using this: exkeys.

void simulate_keypress(int key);
Stuffs a key into the keyboard buffer, just as if the user had pressed it. The parameter is in the same format returned by readkey(). Example:

>           simulate_keypress(KEY_SPACE << 8);
>           if (readkey() == (KEY_SPACE << 8))
>              allegro_message("You simulated Alt+Space\n");

> See also: install_keyboard, simulate_ukeypress, keypressed, readkey.

void simulate_ukeypress(int key, int scancode);
Stuffs a key into the keyboard buffer, just as if the user had pressed it. The parameter is in the same format returned by ureadkey(). Example:

>           /* We ignore the scancode simulation. */
>           simulate_ukeypress(0x00DF, 0);
>           if (ureadkey(&scancode) == 0x00DF)
>              allegro_message("You simulated sharp s\n");

> See also: install_keyboard, simulate_keypress, keypressed, ureadkey.

extern int (*keyboard_callback)(int key);
If set, this function is called by the keyboard handler in response to every keypress. It is passed a copy of the value that is about to be added into the input buffer, and can either return this value unchanged, return zero to cause the key to be ignored, or return a modified value to change what readkey() will later return. This routine executes in an interrupt context, so it must be in locked memory. Example:

>           int enigma_scrambler(int key)
>           {
>              /* Add one to both the scancode and ascii values. */
>              return (((key >> 8) + 1) << 8) | ((key & 0xff) + 1);
>           }
>           END_OF_FUNCTION(enigma_scrambler)

>           ...

>              install_timer();
>              LOCK_FUNCTION(enigma_scrambler);
>              install_keyboard();
>              keyboard_callback = enigma_scrambler;

Note that this callback will be ignored if you also set the unicode keyboard callback.

> See also: install_keyboard, readkey, ureadkey, keyboard_ucallback, keyboard_lowlevel_callback.

extern int (*keyboard_ucallback)(int key, int *scancode);
Unicode-aware version of keyboard_callback(). If set, this function is called by the keyboard handler in response to every keypress. It is passed the character value and scancode that are about to be added into the input buffer, can modify the scancode value, and returns a new or modified key code. If it both sets the scancode to zero and returns zero, the keypress will be ignored. This routine executes in an interrupt context, so it must be in locked memory. Example:

>           int silence_g_key(int key, int *scancode)
>           {
>              if (key == 'g') {
>                 *scancode = 0;
>                 return 0;
>              }
>              return key;
>           } END_OF_FUNCTION(silence_g_key)

>           ...

>              install_timer();
>              LOCK_FUNCTION(silence_g_key);
>              install_keyboard();
>              keyboard_ucallback = silence_g_key;

Note that this keyboard callback has priority over the non unicode callback. If you set both, only the unicode one will work.

> See also: install_keyboard, readkey, ureadkey, keyboard_callback, keyboard_lowlevel_callback.

extern void (*keyboard_lowlevel_callback)(int scancode);
If set, this function is called by the keyboard handler in response to every keyboard event, both presses (including keyboard repeat rate) and releases. It will be passed a raw keyboard scancode byte (scancodes are 7 bits long), with the top bit (8th bit) clear if the key has been pressed or set if it was released. This routine executes in an interrupt context, so it must be in locked memory. Example:

>           volatile int key_down, key_up;

>           void keypress_watcher(int scancode)
>           {
>              if (scancode & 0x80) {
>                 key_up = 1;
>              } else {
>                 key_down = 1;
>              }
>           } END_OF_FUNCTION(keypress_watcher)

>           ...

>              install_timer();
>              LOCK_FUNCTION(silence_g_key);
>              LOCK_VARIABLE(key_down);
>              LOCK_VARIABLE(key_up);
>              install_keyboard();
>              keyboard_lowlevel_callback = keypress_watcher;
>              /* Disable keyboard repeat to get typewriter effect. */
>              set_keyboard_rate(0, 0);

>           ...

>              while (game_loop) {
>                 if (key_down) {
>                    key_down = 0;
>                    /* Play sample of typewriter key press. */
>                 }
>                 if (key_up) {
>                    key_up = 0;
>                    /* Play sample of typewriter key release. */
>                 }
>              }

> See also: install_keyboard, keyboard_callback, keyboard_ucallback.

> Examples using this: exkeys.

void set_leds(int leds);
Overrides the state of the keyboard LED indicators. The parameter is a bitmask containing any of the values KB_SCROLOCK_FLAG, KB_NUMLOCK_FLAG, and KB_CAPSLOCK_FLAG, or -1 to restore the default behavior. Example:

>           /* Cycle led indicators. */
>           set_leds(KB_SCROLOCK_FLAG);
>           rest(1000);
>           set_leds(KB_CAPSLOCK_FLAG);
>           rest(1000);
>           set_leds(KB_NUMLOCK_FLAG);
>           rest(1000);
>           set_leds(-1);

Note that the led behaviour cannot be guaranteed on some platforms, some leds might not react, or none at all. Therefore you shouldn't rely only on them to communicate information to the user, just in case it doesn't get through.

> See also: install_keyboard, key_led_flag.

void set_keyboard_rate(int delay, int repeat);
Sets the keyboard repeat rate. Times are given in milliseconds. Passing zero times will disable the key repeat.

> See also: install_keyboard, readkey, ureadkey.

void clear_keybuf();
Empties the keyboard buffer. Usually you want to use this in your program before reading keys to avoid previously buffered keys to be returned by calls to readkey() or ureadkey().

> See also: install_keyboard, keypressed, readkey, ureadkey.

> Examples using this: Available Allegro examples.

extern int three_finger_flag;
The DJGPP keyboard handler provides an 'emergency exit' sequence which you can use to kill off your program. If you are running under DOS this is the three finger salute, ctrl+alt+del. Most multitasking OS's will trap this combination before it reaches the Allegro handler, in which case you can use the alternative ctrl+alt+end. If you want to disable this behaviour in release versions of your program, set this flag to FALSE.

> See also: install_keyboard.

extern int key_led_flag;
By default, the capslock, numlock, and scroll-lock keys toggle the keyboard LED indicators when they are pressed. If you are using these keys for input in your game (eg. capslock to fire) this may not be desirable, so you can clear this flag to prevent the LED's being updated.

> See also: install_keyboard, set_leds.

Back to contents