1

我想从连接到 SerialPort 的设备中读取信息。我之前使用表单(下面的代码)完成了此操作,但我试图在没有表单的情况下执行此操作,只是将信息存储到字符串数组中。

与表单一起使用的代码:

private void serialPort1_DataReceived(object sender,  System.IO.Ports.SerialDataReceivedEventArgs e)
            {
                string line = port.ReadExisting();              
                this.BeginInvoke(new LineReceivedEvent(LineReceived), line);
            }

        private delegate void LineReceivedEvent(string line);
        private void LineReceived(string line)
        {
            textBox3.AppendText(line);
        }

没有表格我能走多远(DA方法允许在程序中存储变量)。我在最后一行收到以下错误Cannot implicitly convert type 'string' to 'System.IO.Ports.SerialDataReceivedEventHandler'

protected override void SolveInstance(IGH_DataAccess DA)
  {
    string selectedportname;
    DA.GetData(1, ref selectedportname);
    int selectedbaudrate;
    DA.GetData(2, ref selectedbaudrate);
    bool connecttodevice;
    DA.GetData(3, ref connecttodevice);
    bool sendtoprint;
    DA.GetData(3, ref sendtoprint);


    port = new SerialPort(selectedportname, selectedbaudrate, Parity.None, 8, StopBits.One); //Create the serial port
    port.DtrEnable = true;   //enables the Data Terminal Ready (DTR) signal during serial communication (Handshaking)
    port.Open();             //Open the port
    port.DataReceived += port.ReadExisting();                                             

  }
4

1 回答 1

1

假设ReadExisting是一个具有正确参数的方法:

//port.DataReceived += port.ReadExisting();   
  port.DataReceived += port.ReadExisting;   

但错误表明它正在返回一个“字符串”,因此这里还有更多需要解决的问题。

编辑:

看起来应该是:

  port.DataReceived += this.serialPort1_DataReceived;   
于 2012-09-30T20:41:55.923 回答