c#serialport datareceived handler

时间:2014-07-10 06:52:32

标签: c# event-handling

当SerialPort收到数据时,我需要知道自定义参数。自定义参数我知道什么时候我做SerialPort。同时有几个开放端口。 我需要知道哪个端口调用DataRecieved及其自定义参数。

串口数量是动态的(存储在数组中 - 未在下面显示)。

自定义参数应该是一个对象,但也可以是一个字符串。对于每个串口一个自定义参数。 2个端口= 2个customparams。

private void Start()
{
    SerialPort _serialport1 = new SerialPort("COM1", 19200, Parity.None, 8, StopBits.One);
    _serialport1.Type = "Analyzer 1"; // custom parameter ?
    _serialport1.DataReceived += new SerialDataReceivedEventHandle (SerialPort_DataReceived, "Analyzer 1");
    _serialport1.Open();

    SerialPort _serialport2 = new SerialPort("COM2", 19200, Parity.None, 8, StopBits.One);
    _serialport2.Type = "Analyzer 2"; // custom parameter ?
    _serialport2.DataReceived += new SerialDataReceivedEventHandle (SerialPort_DataReceived, "Analyzer 2");
    _serialport2.Open();
}

private void SerialPort_DataReceived(object sender, object e)
{
    string _type = (string)e;

    if(_type == "Analyzer 1")
    {
        // Do something
    }

    if(_type == "Analyzer 2")
    {
        // Do something
    }
}

我应该创建自定义处理程序吗?或自定义类的SerialPort与自定义参数?

2 个答案:

答案 0 :(得分:1)

您无法控制传递给事件处理程序的内容,因为该事件是由SerialPort对象本身引发的。第二个参数始终SerialDataReceivedEventArgs的实例,您无法更改。

但是,您始终可以检查sender参数,以查看哪个SerialPort对象引发了该事件:

private SerialPort _serialport1;
private SerialPort _serialport2;

private void Start()
{
    _serialport1 = new SerialPort("COM1", 19200, Parity.None, 8, StopBits.One);
    _serialport1.DataReceived += new SerialDataReceivedEventHandle (SerialPort_DataReceived, "User Object 1");
    _serialport1.Open();

    _serialport2 = new SerialPort("COM2", 19200, Parity.None, 8, StopBits.One);
    _serialport2.DataReceived += new SerialDataReceivedEventHandle (SerialPort_DataReceived, "User Object 2");
    _serialport2.Open();
}

private void SerialPort_DataReceived(object sender, object e)
{
    string s = null;
    if (sender == _serialPort1)
    {
        s = "User Object 1";
    }
    else if (sender == _serialPort2)
    {
        s = "User Object 1";
    }
    ...
}

作为旁注:局部变量名称不应以下划线开头;该约定通常保留用于字段(即成员变量)。只需使用camelCase作为局部变量。

答案 1 :(得分:1)

我使用的最终代码:

public class SerialPortA : SerialPort
{
   public string DeviceType { get; set; }

   public SerialPortA(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits, string deviceType)
       : this()
   {
       //...
   }
   //...
}

private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{ 
    if ((sender as SerialPortA).DeviceType == "Analyzer 1")
    {
        //...
    }
}