Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# or .NET Flushing Keyboard Buffer

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.

like image 791
Amar Premsaran Patel Avatar asked Jun 10 '09 20:06

Amar Premsaran Patel


5 Answers

while (Console.KeyAvailable) { Console.ReadKey(true); }
like image 182
Chris Avatar answered Oct 05 '22 12:10

Chris


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

like image 26
SLaks Avatar answered Oct 05 '22 14:10

SLaks


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.

like image 32
rein Avatar answered Oct 05 '22 14:10

rein


@Chris:

Console.KeyAvailable threw an exception on me because the Console did not have focus.

The exception message was helpful, though. It suggested using Console.In.Peek() to read in that instance.

I thought it would be worth noting here as an alternate solution and for posterity.

 if (-1 < Console.In.Peek()) {
     Console.In.ReadToEnd();
 }
like image 27
jp2code Avatar answered Oct 05 '22 12:10

jp2code


Disable the form, and force all processing to occur with DoEvents whilst it's disabled. The Controls should reject any keystokes because they are disabled. Then re-enable the form.

this.Enabled = false;
Application.DoEvents();
this.Enabled = true;
like image 22
midspace Avatar answered Oct 05 '22 14:10

midspace