我想从连接到 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();
}