我有一个main(Form1)类,第二个类处理所有串行通信(ComPort)
当通过串口(Event)接收到新数据时,我想将它传递给Form1并对这些数据进行一些操作。 小例子:从接收数据创建长字符串
Form1.cs
public partial class Form1 : Form
{
//Creating instance of SerialCommunication.
....
....
string receivedString = ""; //Here I will store all data
public void addNewDataMethod(string newDataFromSerial)
{
receivedString = receivedString + newDataFromSerial;
MessageBox.Show(receivedString);
}
}
SerialCommunication.cs
public partial class SerialCommunicationPort
{
constructor()
{
.... //open serial port with the relevant parameters
ComPort.DataReceived += new SerialDataReceivedEventHandler(ComPortBufferRead);//Create Handler
}
public void ComPortBufferRead(object sender, SerialDataReceivedEventArgs e)
{
//create array to store buffer data
byte[] inputData = new byte[ComPort.BytesToRead];
//read the data from buffer
ComPort.Read(inputData, 0, ComPort.BytesToRead);
//***** What should I write here in order to pass "inputData" to Form1.addNewDataMethod ?
}
}
我试过以下内容:
Form1 Form;
Form1.addNewDataMethod(inputData.ToString());
上面的代码会产生错误:使用未分配的局部变量“Form”
Form1 Form1 = new Form1();
Form1.addNewDataMethod(inputData.ToString());
以上将创建Form1的新实例,并且不包含先前收到的数据。
任何建议?
答案 0 :(得分:3)
在SerialCommunication
类中创建一个事件,该事件将在数据到达时引发:
public partial class SerialCommunicationPort
{
public event Action<byte[]> DataReceived;
public void ComPortBufferRead(object sender, SerialDataReceivedEventArgs e)
{
byte[] inputData = new byte[ComPort.BytesToRead];
ComPort.Read(inputData, 0, ComPort.BytesToRead);
if (DataReceived != null)
DataReceived(inputData);
}
}
然后在表单中订阅此活动。
public partial class Form1 : Form
{
SerialCommunication serialCommunication;
public Form1()
{
InitializeComponent();
serialCommunication = new SerialCommunication();
serialCommunication.DataReceived += SerialCommunication_DataReceived;
}
private void SerialCommunication_DataReceived(byte[] data)
{
// get string from byte array
// and call addNewDataMethod
}
}
如果您想遵循WinForms的Microsoft编码指南,那么您应该使用Action<byte[]>
委托代替EventHandler<DataReceivedEventArgs>
委托,其中DataReceivedEventArgs
是继承自EventArgs
的类。
答案 1 :(得分:0)
可能最好的方法是使用事件。定义一个EventArgs参数将采用字符串的事件。在Form1中订阅该事件,在您的串行通信类中,只需触发将您想要的字符串传递给eventargs的事件。
你想要的方式应该也可以,但是像这样:
Form1 Form = new Form1();
Form.Show(); // to display it...
/// to other stuff...
Form.addNewDataMethod(inputData); // call the method on the INSTANCE which you opened!
与方法的用法类似,您可以在Form1中定义一个属性:
private string _myString = "";
public string MyString {
private get {
}
set {
string _myString= value;
// to with the string what you want
}
}
然后类似于方法调用
Form.MyString = "abc";
希望这有帮助!