0
votes

I know this has been asked hundred of times, but I haven't been able to find a solution that helps me. I'm using a barcode scanner and I want to be able to get the keys that are typed using just the keydown events. For some reason, I can't use both keydown and keypress events (my keypress events won't run).

I need to be able to get the characters, including hyphens, uppercase letters and dots and also need to detect the enter key.

These are my listeners:

form.KeyDown += new KeyEventHandler(Input_KeyDown);
form.KeyPress += new KeyPressEventHandler(Input_KeyPress);

And these are my methods:

private void TimedOut(object sender, EventArgs e)
{
   _barcode = "";
}

private void Input_KeyDown(object sender, KeyEventArgs e)
{
   _timer.Stop();
   _timer.Start();

   if (e.KeyData == Keys.Enter)
   {
      if (!_barcode.Equals(""))
  {
     this.BarcodeScanned(_barcode, new EventArgs());
  }
   }

   else
   {

   }
}

private void Input_KeyPress(object sender, KeyPressEventArgs e)
{
   _timer.Stop();
   _timer.Start();
   _barcode += e.KeyChar;
}
1
What have you tried thus far? What code do you have to prove your work? Have you looked into the KeyEventArgs class yet?Brian
Showing the current KeyPress event will definitely help we will need to see if you are checking the Char of the Key(s) properly also check to make sure the regional settings are set the same on both machines / environmentsMethodMan
Are you trying to detect cursor keys after it is clicked? What exactly are you trying to accomplish-Greg
I'm trying to store the chars but also detect the enter key.Mr. Adobo
Shouldn't this line here if (e.KeyData == Keys.Enter) be if (e.KeyData == Key.Enter) ? also I think it should be if(e.key ==Key.Enter) insteadMethodMan

1 Answers

1
votes

Your code above works...on a blank form. However there are several things that can interfere with the key events, especially when there are other controls on the page. Make sure that

  • The AcceptButton property isn't set on the form (this will trap the Enter key)
  • That there are no controls on the form with TabStop set to true (might not be viable but give it a go)
  • That the form has focus when you're typing (unlikely given the description but check anyway)
  • That focus is not otherwise on any control in the form when typing, e.g., a TextBox
  • That no other controls are trying to process the KeyPress or KeyDown events and that no other custom events are configured/set anywhere else in your code

One thing I notice is that you are registering the events like so;

form.KeyDown += new KeyEventHandler(Input_KeyDown);

This implies that you are instantiating this form from another place and trying to get it to send its key events to the calling code. Are you sure that the form instance is persisted/saved to a private class level variable or some such?