自己写了个串口通讯类(代码如下),想封装为DLL,可是DataReceviced事件始终不起作用,难道类中调用事件需要特殊方法?
using System.IO.Ports;
namespace SerialPortLibrary
{
public class PortConn
{
private string _value;
private SerialPort _portObj;
public PortConn(string portNum)
{
_portObj = new SerialPort(portNum, 9600, Parity.None, 8, StopBits.One);
_portObj.DtrEnable = true;
_portObj.DataReceived += new SerialDataReceivedEventHandler(portObj_DataReceived);
}
public void PortOpen()
{
if (_portObj.IsOpen)
{
_portObj.Close();
}
else
{
_portObj.Open();
}
}
public void PortClose()
{
_portObj.Close();
}
public void SendCommand(string commandString)
{
_portObj.WriteLine(commandString);
}
public void portObj_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
_value = _portObj.ReadLine();
}
public string GetValue
{
get { return _value; }
}
}
}
PortConn conn = new PortConn();
你需要在事件触发之前,一直保持对 conn 的引用.
//timer检查获取数据 这个是重点 需要自己去提取是否有数据
m_timer = new System.Windows.Forms.Timer();
m_timer.Interval = defaultTimerInterval;
//设置端口的默认值
m_serialPort = new SerialPort();
m_serialPort.ReadBufferSize = 2048;//byte[] size 2048
m_serialPort.BaudRate = 9600; //电子秤默认是9600
m_serialPort.DataBits = 8;
m_serialPort.Parity = Parity.None;
m_serialPort.StopBits = StopBits.One;
m_serialPort.ReadTimeout = 2000;//超时
m_serialPort.PortName = "COM2"; //多数都用COMM
m_serialPort.DataReceived += new SerialDataReceivedEventHandler(m_serialPort_DataReceived);