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.
while (Console.KeyAvailable) { Console.ReadKey(true); }
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
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.
@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();
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With