我被要求编写一个串行端口库来处理应用程序所需的串行端口功能。从主Windows窗体调用库的方法 openComportToTuneSuite(),并设置串口进行通信,包括分配“ portMessageReceivedFromTuneSuite ”引发 comport.DataReceived 事件时的方法。一切似乎都运作良好;但是我无法解决如何使DataReceived方法返回的数据(下面的代码中的“_response”)对主窗口窗体可见。由于在库中设置EventHandler而不是从主Windows窗体调用特定方法的结果(这将允许返回响应)调用此方法,因此没有机会将_response发回申请。
有人可以引导我朝正确的方向指导如何将从DataReceived方法收到的数据从支持库调用到主窗口窗口吗?
图书馆方法
public string openComportToTuneSuite()
{
_tuneSuiteComport.BaudRate = 19200;
_tuneSuiteComport.DataBits = 8;
_tuneSuiteComport.StopBits = StopBits.One;
_tuneSuiteComport.Parity = Parity.None;
_tuneSuiteComport.PortName = "COM11";
_tuneSuiteComport.Handshake = Handshake.None;
_tuneSuiteComport.RtsEnable = true;
_tuneSuiteComport.Open();
_tuneSuiteComport.DataReceived += portMessageReceivedFromTuneSuite;
}
private void portMessageReceivedFromTuneSuite(object sender, SerialDataReceivedEventArgs e)
{
string _response = "";
var responseFromChronos = _tuneSuiteComport.ReadExisting();
var responseArray = responseFromChronos.Split('\r');
foreach (var response in responseArray)
{
_response = _response + response.ToString() + Environment.NewLine;
}
//return _response;
return;
}