Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using EventHandler in C++/CLI

Tags:

c#

c++-cli

-I am trying to use event handler in c++/cli to throw event and then subscribe it in c#

class Mclass
{
 event System::EventHandler ^ someEvent;
 void ShowMessage(System::String ^)
 {
  someEvent(this,message);
 }
}

-but it throws error

error C2664: 'managed::Mclass::someEvent::raise' : cannot convert parameter 2 from 'System::String ^' to 'System::EventArgs ^'

How to rectify it

like image 887
manu_dilip_shah Avatar asked Mar 10 '26 13:03

manu_dilip_shah


2 Answers

The EventHandler delegate type requires an object of type EventArgs as the 2nd argument, not a string. A quick way to solve your problem is to declare your own delegate type:

public:
    delegate void SomeEventHandler(String^ message);
    event SomeEventHandler^ someEvent;

But that's not the .NET way. That starts by deriving your own little helper class derived from EventArgs to store any custom event arguments:

public ref class MyEventArgs : EventArgs {
    String^ message;
public:
    MyEventArgs(String^ arg) {
        message = arg;
    }
    property String^ Message {
        String^ get() { return message; }
    }
};

Which you then use like this:

public ref class Class1
{
public:
    event EventHandler<MyEventArgs^>^ someEvent;

    void ShowMessage(System::String^ message) {
        someEvent(this, gcnew MyEventArgs(message));
    }
};

Note the use of the generic EventHandler<> type instead of the original non-generic one. It is more code than the simple approach but it is very friendly on the client code programmer, he'll instantly know how to use your event since it follows the standard pattern.

like image 168
Hans Passant Avatar answered Mar 12 '26 04:03

Hans Passant


As winSharp93 points out, the signature for System::EventHandler takes a System::EventArgs. You can either:

  1. Create your own EventArgs-derived class that contains the string message you want,

  2. Use your own delegate instead of `System::EventHandler':

    delegate void MyDelegate(string^); event MyDelegate^ someEvent;

like image 36
Moo-Juice Avatar answered Mar 12 '26 04:03

Moo-Juice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!