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

白昼怎懂夜的黑 提交于 2019-12-01 09:45:51

问题


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:


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.



来源:https://stackoverflow.com/questions/8702317/how-to-defocus-a-button-when-barcode-scanner-sent-data-ending-with-newline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!