Avatar of SaltyDawg
SaltyDawg
Flag for United States of America asked on

Get Value of Barcode

I am trying to get the value of a barcode directly into a variable. I am not using a textbox, label or any control to hold the value, I need it in a variable so I can parse it.

The User has a list of Barcodes each acting as a specific command. Any of these Barcodes can be scanned at any time so I would like to be able to parse which command was scanned and execute the appropriate procedure. Ideally to me it sounds simple but I am just not too familiar with how the Barcode Scanner works.

I understand how to focus on a textbox and input value, but not to a variable.

Thanks

FYI: I am using a Wasp Barcode Scanner Model WLR8905
IF relevant.
.NET ProgrammingC#

Avatar of undefined
Last Comment
Antonio kim

8/22/2022 - Mon
Todd Gerbert

Does your barcode scanner use a keyboard wedge?  i.e. If you open Notepad and start scanning, do the scanned values appear in Notepad?
Jarrod

you have to focus to a textbox and scan ....
I would suggest hiding a textbox by moving it off the visable area of the screen (not setting the visibility to false) - then set focus to the textbox.
once the user scans the text is wrtten to the textbox - add an event to the textbox (txtchanged etc .... find one to suite you) then read the data into a variable and clear the textbox.
SaltyDawg

ASKER
@zadeveloper:
This was my first first idea. I was just wondering if there was a simpler way without all the overhead of event handling. Thanks.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
Todd Gerbert

Just something else to throw out there...

You can create a form, set it's KeyPreview to true, and then handle the form's KeyPress event to get the characters scanned one at a time.  You'd have to append them to a string, and need someway to recognize the end of the input. It wouldn't require a text box, is not terribly difficult, but I think zadeveloper's idea is easier.
Todd Gerbert

Assuming of course your barcode scanner is just a keyboard as far as Windows is concerned, anyway, and quick glance at the manual would suggest so.
SaltyDawg

ASKER
@tgerbert:
This is exactly what I was thinking of, just couldn't quite get the KeyPress into a string. Using a textbox would be easier but I am trying to stay away from using that unless I have no choice.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
ASKER CERTIFIED SOLUTION
Todd Gerbert

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Todd Gerbert

And you can go one step further, and implement a BarcodeReceived event for your form.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public delegate void BarcodeReceivedEventHandler(object sender, BarcodeReceivedEventArgs e);

    public class BarcodeReceivedEventArgs : EventArgs
    {
        private string _barcode;
        public BarcodeReceivedEventArgs(string Barcode)
        {
            _barcode = Barcode;
        }
        public string Barcode { get { return _barcode; } }
    }

    public partial class Form1 : Form
    {
        public event BarcodeReceivedEventHandler BarcodeReceived;

        const char ScannerStartCharacter = '~';
        const char ScannerEndCharacter = '\r';

        private StringBuilder scannedCharacters;
        private bool currentlyReadingScanner;

        public Form1()
        {
            InitializeComponent();

            currentlyReadingScanner = false;
            scannedCharacters = new StringBuilder();

            this.KeyPreview = true;
            this.KeyPress += new KeyPressEventHandler(Form1_KeyPress);

            this.BarcodeReceived += new BarcodeReceivedEventHandler(Form1_BarcodeReceived);
        }

        void Form1_BarcodeReceived(object sender, BarcodeReceivedEventArgs e)
        {
            MessageBox.Show("Barcode scanned: " + e.Barcode);
        }

        void Form1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (currentlyReadingScanner)
            {
                if (e.KeyChar == ScannerEndCharacter)
                {
                    currentlyReadingScanner = false;
                    e.Handled = true;
                    OnBarcodeRecieved(new BarcodeReceivedEventArgs(scannedCharacters.ToString()));
                }
                else
                {
                    scannedCharacters.Append(e.KeyChar);
                    e.Handled = true;
                }
            }
            else
            {
                if (e.KeyChar == ScannerStartCharacter)
                {
                    scannedCharacters.Remove(0, scannedCharacters.Length);
                    currentlyReadingScanner = true;
                    e.Handled = true;
                }
            }
        }
        protected virtual void OnBarcodeRecieved(BarcodeReceivedEventArgs e)
        {
            if (BarcodeReceived != null)
                BarcodeReceived(this, e);
        }
    }
}

Open in new window

SaltyDawg

ASKER
Thanks tgerbert, worked out great. Also your example gave me more ideas that helped me out in some other area.
Thanks.
SaltyDawg

ASKER
One more question, you used:
void Form1_KeyPress(object sender, KeyPressEventArgs e)
and I used:
protected override void OnKeyPress(KeyPressEventArgs e)
both seem to work, but what the difference here, which is best?
Your help has saved me hundreds of hours of internet surfing.
fblack61
Todd Gerbert

The difference is that protected override void OnSomeEventName is used to override the base class' implementation of an event. For example, a button's click event causes the button to appear sunken - if I wanted it to appear raised wen clicked instead, I could create my own class, which inherits from Button, and override Button's click behavior.

public class MyButton : Button
{
  protected override void OnClick(EventArgs e)
  {
    RaiseButton();
  }
}

Whereas using this.SomeEventName += void SomeName_SomeEvent(object sender, EventArgs e) is used to subscribe to an event, without affecting how the event is raised.

It probably makes more sense to use your method since really you've created your own class, Form1, which inherits from Form and you're overriding Form's KeyPress behavior. In this particular case, however, the difference between the two is subtle, and for all intents and purposes, they are equivelant so long as you call the base class' OnKeyPress.
SaltyDawg

ASKER
Ok that sounds good. And Thanks for your help
SaltyDawg

ASKER
Thanks for the detailed solution.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
free5945

can you convert it to VB.Net. Thank you
Antonio kim

I used Todd Gerbert Source code.
But Form1_Keypress event runs twice.
So sanner reading value or my pressed key values are also display twice.

What is problem? the source code is almost same.

the source code is below.

Please help me~~~~~
=========================================================================
namespace usb_scanner2
{


    public partial class Form1 : Form
    {
        public delegate void BarcodeReceivedEventHandler(object sender, BarcodeReceivedEventArgs e);

        public class BarcodeReceivedEventArgs : EventArgs
        {

            private string _barcode;

            public BarcodeReceivedEventArgs(string Barcode)
            {

                _barcode = Barcode;

            }

            public string Barcode { get { return _barcode; } }

        }

        public event BarcodeReceivedEventHandler BarcodeReceived;

        const char ScannerEndCharacter = '\r';

        private StringBuilder scannedCharacters;

        public Form1()
        {
            InitializeComponent();

            scannedCharacters = new StringBuilder();

            this.KeyPreview = true;
            this.KeyPress += new KeyPressEventHandler(Form1_KeyPress);

            this.BarcodeReceived += new BarcodeReceivedEventHandler(Form1_BarcodeReceived);
        }

        void Form1_BarcodeReceived(object sender, BarcodeReceivedEventArgs e)
        {

            MessageBox.Show("Barcode scanned: " + e.Barcode);

        }

        protected virtual void OnBarcodeRecieved(BarcodeReceivedEventArgs e)
        {

            if (BarcodeReceived != null)

                BarcodeReceived(this, e);

        }

        private void Form1_KeyPress(object sender, KeyPressEventArgs e)
        {
                if (e.KeyChar == 13)    //ScannerEndCharacter)
                {
                    e.Handled = true;
                   
                    OnBarcodeRecieved(new BarcodeReceivedEventArgs(scannedCharacters.ToString()));
                    scannedCharacters.Remove(0, scannedCharacters.Length);
                }

                else
                {
                    Debug.Print(e.KeyChar.ToString());
                    scannedCharacters.Append(e.KeyChar);
                    e.Handled = false;
                }
        }
    }
}