我想从连接到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();
}
答案 0 :(得分:1)
假设ReadExisting
是一个具有正确参数的方法:
//port.DataReceived += port.ReadExisting();
port.DataReceived += port.ReadExisting;
但错误表明它正在返回一个'字符串',因此这里有更多要解决的问题。
看起来应该是:
port.DataReceived += this.serialPort1_DataReceived;