catch input from a magnetic card reader to a varia

2019-03-02 16:56发布

问题:

I can't seem to find a way to catch the input of a magnetic card reader. When it swipes, the input gets into active text editor, like say a notepad.

Unfortunately, the focus on textbox field won't do the trick, because I'm required to make it a label instead of a textbox. Thus, I need a way to catch the input from the USB device to a variable or label instead.

Does anyone knows of a .NET class I could use to do this or any better ideas?

回答1:

I don't think there will be anyway for you to prevent the user from manual input. I suspect the card reader that you have emulates a keyboard. So, to be able to read from the reader, you must receive keyboard input, and keyboard input means the user can type anything they like.

A possible solution is to change your card reader to one that uses an API to read from cards.

If getting a better card reader isn't an option, I think the best method to do this is to have a button. When the button is clicked, open a new form that contains the code @Bala R provided. But in addition, close the form within 1 second from the first key input. This will prevent users from tampering the input manually, but will provide sufficient time for the reader to complete.



回答2:

If it's a winforms app you could do

    private void Form1_Load(object sender, EventArgs e)
    {
        KeyPreview = true;
        KeyPress += Form1_KeyPress;
    }

    private bool inputToLabel = true;
    void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (inputToLabel)
        {
            label1.Text = label1.Text + e.KeyChar;
            e.Handled = true;
        }
        else
        {
            e.Handled = false;
        }
    }

and as long as the window has focus, the keypress characters will go to the label's text.