C# or .NET Flushing Keyboard Buffer

2019-02-17 11:12发布

问题:

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:

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.



回答2:

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



回答3:

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



回答4:

@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();
 }


回答5:

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;


回答6:

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.



回答7:

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