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
@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();
}
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.
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;
while (Console.KeyAvailable) { Console.ReadKey(true); }
It's a old question but I got the same issue and I found a good way to do it...
When Application.DoEvent() is called, the keystoke buffer call the KeyPress event but _keypress is set to false, so it'll skip all them, after that _keypress return to true to be ready for another keypress event !
Public _keypress As Boolean
Private Sub Form1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Form1.KeyPress
If Not _keypress Then
_keypress = True
//instructions
End If
Application.DoEvents()
_keypress = False
End Sub
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