20 aprile 2013

How use USB Magnetic Stripe Reader in C#





USB Magnetic Stripe Reader
A magnetic stripe reader is a hardware device that reads the information encoded in the magnetic stripe located on the back of a plastic badge.

We can use it to read the information contained in the magnetic cards.

Below I post the C# code in order to capture the swipe:





  1. Add the event:
    public Form1()
            {
                InitializeComponent();
                KeyPreview = true;
                KeyPress += Form1_KeyPress;
            }
  2. Manage the event KeyPress in the form:
    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;
                }
                if (e.KeyChar == (char)Keys.Enter) // if is the last char I do something
                {
                    // I do something
                }
            }
Remember: before you swipe the card, put the focus on the form or textbox where you want put the information read.

Please let me know if you have problems.

Nessun commento: