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
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.