I'm trying to catch the input of the swiped card but I'm stuck using C# Windows Forms

こ雲淡風輕ζ 提交于 2020-01-06 15:44:12

问题


I am using a test card and this is the output after I swiped the card and it is ok

But when I'm trying to get the data of the swiped through prompting it to messagebox this will be the output

How can I fix this? I am expecting the output same as the first image, and it will also be the message of the messagebox

Here is my code:

private void CreditCardProcessor_Load(object sender, EventArgs e)
        {
            KeyPreview = true;
            KeyPress += CreditCardProcessor_KeyPress;
        }
    private bool inputToLabel = true;
        private void CreditCardProcessor_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (inputToLabel)
            {
                label13.Text = label13.Text + e.KeyChar;
                e.Handled = true;

            }
            else
            {
                e.Handled = false;
            }

            MessageBox.Show(label13.Text);
        }

In short I want to run a function after swiping the card, and use its data to be use in my function. :)


回答1:


You'll need to be more specific with your question. From the looks of things your card scanner is operating through the keyboard buffer. (Many card scanners operate this way) This means that every character of the strip is received as a character which is why you can capture this OnKeyPress.

If you're wondering why you're only seeing one character at a time it is exactly because you're raising a message box with each character received. If you want to know when you can call a function with the whole card info using that code what you'll need is something like:

private bool inputToLabel = true;
private StringBuilder cardData = new StringBuilder();
private void CreditCardProcessor_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!inputToLabel)
            return;

        if (e.KeyChar == '\r')
        {
            MessageBox.Show(cardData.ToString()); // Call your method here.
        }
        else
        {
            cardData.Append(e.KeyChar);
            //label13.Text = label13.Text + e.KeyChar;
        }
        e.Handled = true;
    }

Caveat: This is assuming that the card reader library is configured to terminate a card read with carriage return. (\r) You'll need to read up, or experiment with it for settings as to whether it can/does send a terminating character to know when the card read is complete. Failing that you can watch the output string for patterns. (I.e. when the captured string ends with "??") Though this is less optimal.



来源:https://stackoverflow.com/questions/13757948/im-trying-to-catch-the-input-of-the-swiped-card-but-im-stuck-using-c-sharp-win

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