C # or .NET Flushing Keyboard Buffer

How to clear keyboard buffer in C # using Windows Forms?

I have a barcode scanner that acts like a keyboard. If a really long barcode is scanned and the cancel button is pressed on the form, I need the keyboard buffer to be cleared. Therefore, I need to clear and ignore all pending input. I need to clear the buffer because if the barcode contains spaces, spaces are treated as keystrokes that are not needed.

+6
c # keyboard buffer flush
source share
7 answers

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

The event loop will only go to your undo action after processing the keystrokes. You can only cancel keystrokes based on any event that occurs in the middle of a keystroke sequence.

+1
source share

Set KeyPreview on the form to true , then catch the KeyPress event and set e.Handled to true if canceled.

EDIT : Output KeyPress Form Event

+2
source share

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

+2
source share

@Chris:

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

However, the exception message was useful. He suggested using Console.In.Peek() to read in this case.

I thought it was worth mentioning an alternative solution for posterity.

  if (-1 < Console.In.Peek()) { Console.In.ReadToEnd(); } 
+1
source share

Disable the form and force all processing with DoEvents while it is disabled. Controls must reject any keys since they are disabled. Then turn on the form again.

 this.Enabled = false; Application.DoEvents(); this.Enabled = true; 
+1
source share

You can do a BIOS level cleanup ( http://support.microsoft.com/?scid=kb%3Ben-us%3B43993&x=22&y=10 ), but I would recommend using this low level approach, since Windows also performs keyboard buffering more high level.

The best way is to eat any inbound char while a certain flag is set. As SLaks suggests, I would set KeyPreview to true and set e.Handled to true either in KeyPress or in KeyDown .. shouldn't matter.

0
source share

This is an old question, but I have the same problem and I found a good way to do this ...
When Application.DoEvent () is called, the key buffer raises a KeyPress event call, but _keypress is false, so it will skip all of them, after which _keypress will return to true to be ready for another keystroke 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 
0
source share

All Articles