问题
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