1. Connect the barcode scanner: Connect the barcode scanner to the computer via USB or serial port. Ensure the driver is installed and working properly. 2. Create a serial port object: Use the SerialPort class in C# to create a serial port object to receive data sent by the scanner. csharpCopy code
SerialPort serialPort = new SerialPort();
serialPort.PortName = "COM1"; //Specify the serial port number
serialPort.BaudRate = 9600; //Specify the baud rate
serialPort.Open(); //Open the serial port
3. Read data: Use the serial port object's DataReceived event to listen for data sent by the scanner. This event is triggered when data arrives, and then the data is read and processed. csharpCopy code
serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
Console.WriteLine("Data Received:");
Console.WriteLine(indata);
}
4. Closing the serial port: When the program no longer needs to receive data from the scanner, close the serial port object to release resources. csharpCopy code
serialPort.Close(); //Close the serial port
Note that different scanner models may have different data formats and communication protocols. Therefore, in actual applications, it is necessary to understand the scanner's specific specifications and operating instructions to correctly process and parse the data sent by the scanner.