How to defocus a button when barcode scanner sent

2019-02-19 16:58发布

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. Here is my problem:

I have a reset button in the form which clears all fields and barcodes listed in a dataGridView. When I clicked on it, it gets focus as normal. When it has focus, if I read a barcode via barcode scanner, the newline at the end of each barcode reading causes this button to be clicked thus clearing all fields. So barcodes read are added to dataGridView but immediately deleted due to activation of reset button.

My current solution is to focus on a read-only textbox at the end of each "button_Click" function, but I don't want to write an irrelevant line at the end of each "click" function of buttons. What do you recommend? (by the way I cannot prevent surpress enter key in form's keydown function)

1条回答
劫难
2楼-- · 2019-02-19 17:39

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.

查看更多
登录 后发表回答