catch input from a magnetic card reader to a variable

Corbee picture Corbee · Mar 24, 2011 · Viewed 10.9k times · Source

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?

Answer

Bala R picture Bala R · Mar 24, 2011

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.