我从串口接收数据并使用此方法MSDN source:
static void DataReceivedHandler(
Object^ sender,
SerialDataReceivedEventArgs^ e)
{
SerialPort^ sp = (SerialPort^)sender;
String^ indata = sp->ReadExisting();
System::Diagnostics::Debug::Write("Data Received:");
System::Diagnostics::Debug::Write(indata);
}
我可以阅读这些数据。但因为它是静态函数,我无法访问我的GUI窗口对象,我无法将数据写入textBox小部件。
问题是已知的(例如C# related question),我知道我应该使用自己的delegate
,但我不熟悉C ++和C#,经过长时间的努力,我不知道如何使用它
我删除了DataReceivedHandler
和this->mySerialPort->DataReceived += gcnew SerialDataReceivedEventHandler(DataReceivedHandler);
以及我现在拥有的内容(setDelegates
在表单构造函数中调用):
private: delegate void UpdateUiTextDelegate(String^ text);
UpdateUiTextDelegate^ myDelegate;
private: void setDelegates(void) {
myDelegate = gcnew UpdateUiTextDelegate(this,AddDataMethod);
}
public: void AddDataMethod(String^ myString)
{
this->readTextBox->AppendText(myString);
}
private: void mySerialPort_DataReceived(Object^ sender, SerialDataReceivedEventArgs^ e)
{
SerialPort^ sp = (SerialPort^)sender;
String^ s= sp->ReadExisting();
readTextBox->Invoke(this->myDelegate, s);
}
但mySerialPort_DataReceived
函数未被调用,我看不到数据。
你能帮忙解决这个问题吗?