我已将此代码改编为ASP .NET Web表单https://www.codeproject.com/Articles/75770/Basic-serial-port-listening-application
当我使用COM端口数据模拟器进行测试时,它可以正常工作,但是当我尝试真正的扫描仪时,它只显示使用特定QR码的最后一个单词,而其他单词则不显示任何内容。我让我在这里使用的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO.Ports;
using System.IO;
using System.Text;
using System.Threading;
namespace Web_BarcodeScanner
{
public partial class WFScanner : System.Web.UI.Page
{
SerialPortManager _spManager = new SerialPortManager();
protected void Page_Load(object sender, EventArgs e)
{
//SerialSettings mySerialSettings = _spManager.CurrentSerialSettings;
_spManager.CurrentSerialSettings.PortName = "COM5";
_spManager.CurrentSerialSettings.BaudRate = 9600;
_spManager.CurrentSerialSettings.DataBits = 8;
_spManager.CurrentSerialSettings.Parity = Parity.None;
_spManager.CurrentSerialSettings.StopBits = StopBits.One;
_spManager.NewSerialDataRecieved += new EventHandler<SerialDataEventArgs>(_spManager_NewSerialDataRecieved);
}
private void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e)
{
// string str = System.Text.Encoding.Default.GetString(e.Data);
string str = Encoding.ASCII.GetString(e.Data);
TextBox1.Text = str;
}
protected void btnStart_Click(object sender, EventArgs e)
{
_spManager.StartListening();
Thread.Sleep(10000);
}
protected void btnClose_Click(object sender, EventArgs e)
{
_spManager.StopListening();
}
}
}
这是SerialPortManager类中的DataReceived方法:
private SerialPort _serialPort = new SerialPort();
public event EventHandler<SerialDataEventArgs> NewSerialDataRecieved;
.. .. .. ..
void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int dataLength = _serialPort.BytesToRead;
byte[] data = new byte[dataLength];
int nbrDataRead = _serialPort.Read(data, 0, dataLength);
if (nbrDataRead == 0)
return;
if (NewSerialDataRecieved != null)
NewSerialDataRecieved(this, new SerialDataEventArgs(data));
}