How to defocus a button when barcode scanner sent data ending with newline

前端 未结 1 468
日久生厌
日久生厌 2021-01-15 14:55

I am writing a C# barcode application. I have a EAN-13 regex to detect barcodes in \"Form1_KeyPress\" function. I have no mechanism to detect where the input comes from. Her

相关标签:
1条回答
  • 2021-01-15 15:51

    You can't capture the Enter key in the form's keystroke events because it is handled by the button.

    If you add:

    private void button_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            e.IsInputKey = true;
        }
    }
    

    to a button then the Enter key won't cause the button to be clicked, and you will see a Form_KeyDown event for it.

    You don't want to add this to every button, so create a simple UserControl which is just a button with this code added.

    Update

    This doesn't work for the space bar. If you set form.KeyPreview = true and add:

    private void form_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Space)
        {
            e.Handled = true;
        }
    }
    

    then the space bar won't press the button but it will still work in text boxes.

    I don't know why Space and Enter behave differently.

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