C# or .NET Flushing Keyboard Buffer

后端 未结 7 1356
太阳男子
太阳男子 2021-01-12 08:34

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

相关标签:
7条回答
  • 2021-01-12 09:09

    @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();
     }
    
    0 讨论(0)
  • 2021-01-12 09:09

    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.

    0 讨论(0)
  • 2021-01-12 09:12

    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;
    
    0 讨论(0)
  • 2021-01-12 09:15
    while (Console.KeyAvailable) { Console.ReadKey(true); }
    
    0 讨论(0)
  • 2021-01-12 09:15

    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
    
    0 讨论(0)
  • 2021-01-12 09:20

    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

    0 讨论(0)
提交回复
热议问题