using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;
namespace _0080828
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//声明一个串口
System.IO.Ports.SerialPort port = new System.IO.Ports.SerialPort();
//声明一个字节数组来存放从扫码枪中读出的数据
Byte[] data = new byte[90000];
//声明已读了多少数据
int count = 0;
private void Form1_Load(object sender, EventArgs e)
{
//设置扫码枪使用的串口名称
port.PortName = "COM4";
//打开此串口
port.Open();
//声明扫码枪的每次触发会执行函数xlh
port.DataReceived += new SerialDataReceivedEventHandler(xlh);
}
public void xlh(object sender, SerialDataReceivedEventArgs e)
{
//将扫码枪中的数据显示出来
MessageBox.Show(getData());
}
public String getData()
{
//取出扫码枪中的数据总数
int length = port.BytesToRead;
for (int i = 0; i < length;i++ )
{
//每次从扫码枪中读出一个字节的数据
data[count] = (byte)port.ReadByte();
count++;
}
//声明字节转字符类
UTF8Encoding enc = new UTF8Encoding();
//将扫码枪中的字节数组转换成字符串
String returnDate = enc.GetString(data);
//返回字符串
return returnDate;
}
}
}