INT 21h AH=0Bh answers one question: is input waiting at standard input? It returns AL = FFh if a key is there and 00h if not, without waiting and without taking the key. A following read then returns at once.
MOV AH, 0Bh ; DOS: is a key waiting?INT 21h ; AL = 00h: the buffer is emptyCALL HEX2MOV CX, 2D78h ; "x": scan code 2Dh, ASCII 78hMOV AH, 05h ; BIOS: store a keystroke in the keyboard bufferINT 16hMOV DL, " "MOV AH, 02h ; DOS: print the character in DLINT 21hMOV AH, 0BhINT 21h ; AL = FFh: now there is oneCALL HEX2MOV DL, " "MOV AH, 02h ; DOS: print the character in DLINT 21hMOV AH, 07h ; 0Bh left the key there: take it outINT 21hMOV DL, ALMOV AH, 02h ; DOS: print the character in DLINT 21hHEX2 PROC NEAR ; print AL as two hex digitsPUSH AXMOV CL, 4SHR AL, CL ; the high digit firstCALL NIB1POP AXAND AL, 0Fh ; then the low oneCALL NIB1RETHEX2 ENDPNIB1 PROC NEAR ; print AL (0-15) as one hex digitADD AL, "0"CMP AL, "9"JBE NIB2ADD AL, 7 ; 10-15 become "A"-"F"NIB2:MOV DL, ALMOV AH, 02hINT 21hRETNIB1 ENDP
The example asks twice, before and after putting an "x" into the BIOS keyboard buffer with INT 16h AH=05h, then reads the key to show it was still there. The usual use is a loop that works until a key is pressed:
WORK1:; ... one step of the work ...MOV AH, 0Bh ; DOS: is a key waiting?INT 21hTEST AL, ALJZ WORK1 ; 00h: no, go on workingMOV AH, 07h ; take the key out of the bufferINT 21h
Take the key out when the loop ends. Left in the buffer it is read by whatever reads next, often COMMAND.COM, which then shows it at the prompt.
Pitfalls
MS-DOS checks for Ctrl+C here as in the other console services: a waiting Ctrl+C makes 0Bh print ^C and end the program. That is a feature in a work loop, where Ctrl+C stops it, and a surprise in a program that wanted to read Ctrl+C itself; INT 21h AH=06h with DL = FFh asks the same question without the check, taking the key at the same time. With input redirected from a file, 0Bh reports FFh until the file ends. The BIOS has the same test one level down, INT 16h AH=01h, which also tells which key is waiting. DOSBox-X slows each 0Bh call down a little, as a real DOS would be, because some old games depend on that.