FlushKeys
Parameters
| None. |
Description
|
Throws away pending key presses so old input cannot leak into the next screen. Every key press is recorded twice: as a count that KeyHit hands out, and as a character sitting in the queue that GetKey reads. FlushKeys clears both in one go. You want it whenever the game changes context. A player mashing Space to kill the last enemy should not instantly skip the victory screen, and keys pressed during a long level load should not fire the moment play begins. Call FlushKeys just before you show the new screen and the slate is clean. It is also the fix for the classic "my menu picked two items at once" bug: flush after you act on a selection, so the keystroke that opened a submenu is not still queued when the submenu starts reading input. One thing it deliberately does not do is release keys that are physically still held. KeyDown reports the live state of the keyboard, so a key the player has not let go of still reads 1 immediately after a flush. If you need "wait until they let go", loop until KeyDown returns 0. See also: KeyHit, GetKey, KeyDown, WaitKey, FlushMouse, FlushJoy. |
Example
; FlushKeys Example ; ----------------- Graphics 640,480,0,2 SetBuffer BackBuffer() ; Keypresses queue up in a buffer until your program reads them. ; FlushKeys empties that queue - call it before a "press a key" ; prompt so an old, stale keypress cannot skip it. flush_mode=1 quit=0 Repeat ; Start each round with an empty queue FlushKeys ; Phase 1: let keypresses pile up unread for three seconds finish=MilliSecs()+3000 While MilliSecs()<finish If KeyDown(1) Then Exit Cls Text 0,0,"Mash some letter keys NOW - they are queuing up unread!" Text 0,20,"Time left: "+((finish-MilliSecs())/1000+1) If flush_mode Then Text 0,40,"FlushKeys WILL be called before the queue is read." Else Text 0,40,"FlushKeys will NOT be called - watch the queue survive." End If Flip Wend ; Phase 2: optionally flush, then read whatever survived used_flush=flush_mode If flush_mode Then FlushKeys ; the documented command - empties the buffer caught$="" k=GetKey() While k>0 If k>=32 And k<=126 Then caught$=caught$+Chr$(k) k=GetKey() Wend ; Discard Space/F presses made while mashing so the menu below ; does not trigger instantly dummy=KeyHit(57)+KeyHit(33) ; Phase 3: show the result and offer another run done=0 While done=0 Cls Text 0,0,"Space: run again F: toggle FlushKeys Esc: exit" Text 0,40,"Keys read from the buffer: '"+caught$+"'" If used_flush Then Text 0,60,"FlushKeys was called first, so the queue came back empty." Else Text 0,60,"No flush - every buffered press was still waiting." End If If flush_mode Then Text 0,100,"Next run: FlushKeys ON" Else Text 0,100,"Next run: FlushKeys OFF" End If Flip If KeyHit(57) Then done=1 If KeyHit(33) Then flush_mode=1-flush_mode If KeyDown(1) Then quit=1 If quit Then done=1 Wend Until quit End
Index