Capturing Carriage Return

  • Thread starter Thread starter senfo
  • Start date Start date
S

senfo

Hello all,

To help alleviate human error, I'm developing an application that uses a
barcode reader to fill in a value in a TextBox control. The barcode
reader is connected to the PC through the PS2 keyboard jack, so to
Windows, it's essentially just a keyboard. After the reader has
finished reading the barcode, it sends out Ctrl + M (which I *think* is
a carriage return).

To capture the Ctrl + M, I configured an event handler for the
PreviewKeyDown event. In the event handler, I have tried the following:

private void MyTextBox_PreviewKeyDown(object sender,
PreviewKeyDownEventArgs e)
{
// First way I tried
if (e.Control && e.KeyCode == Keys.M)
{
ShowNewDialog();
}

// Second way I tried
if ((int) e.KeyData == (int) (Keys.M | Keys.Control))
{
ShowNewDialog();
}
}

Essentially, both of them do the same thing, but the first one is less
confusing to somebody that reads my code later.

At any rate, the code works --kind of. The problem is that after
ShowNewDialog() returns, the letter "m" shows up in the MyTextBox
control. If I comment out the call to ShowNewDialog(), the letter "m"
never shows up.

Short of an ugly "fix", such as removing the letter "m" after
ShowNewDialog() returns, I'm not sure what else to do. I was hoping
there was a better way of capturing the carriage return that I haven't
thought of.

Any suggestions?

Thank you in advance,
 
Hi,

Any reason for using PreviewKeyDown instead of KeyDown?

If you are using KeyDown you can use the KeyEventArgs.Handled = true to
suppress keys
 
Morten said:
Any reason for using PreviewKeyDown instead of KeyDown?

If you are using KeyDown you can use the KeyEventArgs.Handled = true to
suppress keys

Hi Morten,

That's a good question and I don't have an answer for you. Using the
KeyDown event fixed everything.

Thank you very much!
 
Back
Top