2

I receive data from serial port and with this method 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);
}

I can read this data. But because it is static function I don't have access to my GUI window objects and I can't write data to textBox widget. The problem is known (e.g. C# related question) and I know I should use my own delegate, but I'm not familiar with C++ and C# and after my quite long struggle I don't know how to use it.

I removed DataReceivedHandler and this->mySerialPort->DataReceived += gcnew SerialDataReceivedEventHandler(DataReceivedHandler); and what I have now (setDelegates is called in Form constructor):

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);

}

But mySerialPort_DataReceived function is not called and I don't see data.

Can you help with this?

Community
  • 1
  • 1
bLAZ
  • 1,689
  • 4
  • 19
  • 31
  • Did you subscribe to the `DataReceived` event of the `SerialPort` using your method `mySerialPort_DataReceived`? – David Yaw Mar 19 '14 at 15:43
  • You mean something like: ` this->mySerialPort->DataReceived += gcnew SerialDataReceivedEventHandler(mySerialPort_DataReceived); ` ? I forgot about it, but now I get error when I put this line:`error C3350: 'System::IO::Ports::SerialDataReceivedEventHandler' : a delegate constructor expects 2 argument(s)` – bLAZ Mar 19 '14 at 15:49
  • So just don't make it a static function. It can be an instance method of the form that contains that textbox. .NET supports that well. – Hans Passant Mar 19 '14 at 17:18
  • 1
    Here's the syntax for creating instance delegates: `gcnew WhateverHandler(objectInstance, &ObjectClass::InstanceMethodName)`. For a delegate to a static method, pass just one parameter. – David Yaw Mar 19 '14 at 17:31
  • It works with `this->mySerialPort->DataReceived += gcnew SerialDataReceivedEventHandler(this, &Form1::mySerialPort_DataReceived);`. Thanks a lot! – bLAZ Mar 20 '14 at 10:17
  • 1
    How to mark it as solved without answer? – bLAZ Mar 20 '14 at 10:32
  • @bLAZ Yes. The comment box even says "avoid answering questions in comments". You could write an answer (and accept it) yourself. That would best help other people with the same question. – Tom Blodget Mar 21 '14 at 03:48

0 Answers0