views:

1422

answers:

4

How do I flush the keyboard buffer in C# using Windows Forms?

I have a barcode scanner which acts like a keyboard. If a really long barcode is scanned and the cancel button is hit on the form, I need the keyboard buffer to be cleared. So I need to flush and ignore all pending input. I need the buffer cleared because if the barcode contains spaces, the spaces are processed as button clicks which is unecessary.

+1  A: 

Set KeyPreview on the Form to true, then catch the KeyPress event and set e.Handled to true if cancel was clicked.

EDIT: Catch the Form's KeyPress event

SLaks
+1  A: 

I'm not sure you can do this. The keystrokes go into the event queue for the main event loop. Any action you take to cancel these keystrokes will be placed in the queue after the keystrokes.

The event loop will only get to your cancel action after the keystrokes have been processed. You can only cancel the keystrokes based on some event that happens in the middle of the keystroke sequence.

rein
A: 

You could do BIOS level flushing (http://support.microsoft.com/?scid=kb%3Ben-us%3B43993&x=22&y=10) but I would advise against this low level approach since Windows also does keyboard buffering on a higher level.

The best way seems to be to eat any arriving char while a specific flag is set. As SLaks suggests I would set KeyPreview to true and set e.Handled to true either in KeyPress or in KeyDown.. should make no difference.

VVS
A: 

while (Console.KeyAvailable) { Console.ReadKey(true); }

Chris