keyboarddosx86-16basicturbo-basic

Is there a way to read the Keyboard Modifier Keys such as ALT or CTRL in DOS-based programs?


I do know that you might poll the keyboard buffer to get the Modifier Keys such as ALT or CTRL. But even in old DOS Programs there was an action whenever I just pressed these keys (eg. to change the Color of the MENU buttons by pressing ALT). Is there a way in DOS to get these Keys? How is this to be done? I think in BASIC there would be no solution although BASIC has some ON KEY() event handler available. Any recommendations or advises to this question are welcome.


Solution

  • You can look at the KeyboardStatusFlags at linear address 1047 in the BIOS data area. For the Alt key you examine bit 3, and for the Ctrl key you examine bit 2. Next QBASIC program does exactly that:

    DEF SEG = 0
    DO
      IF PEEK(1047) AND 8 THEN
        PRINT "ALT is pressed"
        EXIT DO
      ELSEIF PEEK(1047) AND 4 THEN
        PRINT "CTRL is pressed"
        EXIT DO
      END IF
    LOOP
    

    Answering a comment

    Is there also a way to get the KEY Pressed (ASCII VALUE) by peeking an address?

    Again you can find this info in the keyboard buffer (a circular buffer). BIOS maintains a word-sized pointer to the place where the next available key is stored (HEAD), and a word-sized pointer to the place behind where the most recently buffered key is stored (TAIL). If HEAD equals TAIL, then the keyboard buffer is empty. INKEY$ would return an empty string in this case.

    Head% = PEEK(1050) + 256 * PEEK(1051)
    Tail% = PEEK(1052) + 256 * PEEK(1053)
    IF Head% <> Tail% THEN
      Ascii% = PEEK(1024 + Head%)
      Scan% = PEEK(1024 + Head% + 1)
    ELSE
      Ascii% = 0
      Scan% = 0
    END IF
    

    The 'advantage' of above code is that you can preview what key (if any) is available next in the keyboard buffer. The key is not removed. INKEY$ can give the same info but will remove the key also.