2

I have a application that reads data from health cards and parse them for basic info like D.O.B., Health Card #, and names. Right now, I have a textbox that takes input from the card swiper and it works great, but I feel there could be a better approach for this.

I want to have a keyboard listener in the background of the application that captures input from the card swiper and parse the data without the need of a textbox. I figure I'll need a loop function in the Form1_Load that actively listens for keyboard inputs, prepare a buffer for the input, and then when a carriage return is detected, go ahead and parse the buffered data. When the parsing is done, clear the buffer.

My problem is I'm relatively new to C# and I don't know what I should use for listening to keyboard inputs without a textbox. Could someone point me in the right direction?

Here's my code in case if anyone's interested: http://pastebin.com/q6AkghvN

Just a note, I followed the credit card swipe guide from http://www.markhagan.me/Samples/CreditCardSwipeMagneticStripProcessing and modified it slightly for my usecase.

--- EDITED ---

Thanks Paul and everyone else for their help!

Here is my solution if anyone is interested:

private void frmMain_KeyPress(object sender, KeyPressEventArgs e)
    {
        lblStatus.Text = "Reading Card...";
        lblStatus.ForeColor = Color.Blue;
        if (e.KeyChar != (char)Keys.Enter)
        {
            buffer += e.KeyChar;
        }
        else
        {
            lblStatus.Text = "Parsing Card...";
            if (buffer.Contains('^') && buffer.Contains(';') && buffer.Contains('='))
            {
                try
                {
                    string[] cardData = buffer.Split(';');
                    string[] caretData = cardData[0].Split('^');
                    string[] nameData = caretData[1].Split('/');
                    string[] equalData = cardData[1].Split('=');
                    tBoxHealthCardNumber.Text = equalData[0];
                    tBoxDateOfBirth.Text = FormatBirthday(equalData[1]);
                    tBoxFirstName.Text = TrimName(nameData[1]);
                    tBoxLastName.Text = TrimName(nameData[0]);
                    tBoxDateTimeScanned.Text = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm");
                    e.Handled = true;
                }
                catch (Exception)
                {
                    throw;
                }
            }
            else
            {
                lblStatus.Text = "Error Reading Card";
            }

            buffer = "";
            lblStatus.Text = "Ready";
            lblStatus.ForeColor = Color.Green;
        }
    }
4

1 回答 1

3

如果您将按键处理程序添加到表单,当焦点位于控件(例如文本框)上时,您将看不到按键。为了使表单即使在有焦点控件时也能看到按键,您还必须启用KeyPreview属性。

然后,您可以根据需要添加处理程序KeyDownKeyPress和/或KeyUp在表单上接收这些事件。

正如您在文档中看到的那样KeyPreview,如果您将该Handled属性设置为 true,则可以防止事件随后发送到焦点控件,即您可以隐藏某些关键事件,使其不被焦点控件看到。

于 2013-01-17T14:16:00.400 回答