manu_dilip_shah
manu_dilip_shah

Reputation: 900

Using EventHandler in 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

Upvotes: 2

Views: 8219

Answers (3)

Hans Passant
Hans Passant

Reputation: 941317

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.

Upvotes: 9

Moo-Juice
Moo-Juice

Reputation: 38825

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;

Upvotes: 3

Matthias
Matthias

Reputation: 12259

You can't pass a String to an EventHandler as the second parameter.

Instead, try:

someEvent(this, System::EventArgs::Empty)

If you need to pass custom data, you can create a subclass of EventArgs and use System::EventHandler<TEventArgs>.

Upvotes: 2

Related Questions