How to assign an event handler to an event in C ++ / CLI?

How to add "events" to an "event" / delegate? What is the syntax? Is it the same in C ++ / CLI and in C #?

+6
c # event-handling events c ++ - cli
source share
3 answers

In C # , you do this with += :

 someObj.SomeEvent += new EventHandler(Blah_SomeEvent); 

...

 private void Blah_SomeEvent(object sender, EventArgs e) { } 

More than a year or later change

It has been a long time since I posted this answer, and someone noticed me that maybe this was wrong. I really don't know why the OP marked my answer as correct (maybe the OP was looking for this, not C ++ - cli syntax? Who knows now).

Anyway, in C ++ - cli , it should be:

 someObj->SomeEvent+= gcnew EventHandler(this, &Blah_SomeEvent); 
+11
source share

1: If an invalid event event is custom, you define yourself to be the memeber class (example from MSDN ):

 delegate void Del(int, float); ref class EventReceiver { public: void Handler(int i , float f) { } }; myEventSource->MyEvent += gcnew Del(myEventReceiver, &EventReceiver::Handler); 

2: If the main delegate is a global handler and has a standard signature for .NET events (object + event args) (from the DPD answer):

 delegate void MyOwnEventHandler(Object^ sender, EventArgs^ e) { } myEventSource->MyEvent += gcnew EventHandler(MyOwnEventHandler); 

3: If the main delegate has a standard signature for .NET events, and the event handler is a class method:

 ref class EventReceiver { public: void Handler(Object^ sender, EventArgs^ e) { } }; myEventSource->MyEvent += gcnew EventHandler(myEventReceiver, &EventReceiver::Handler); 

4: Using System :: EventHandler generic (which takes the args parameter MyEventArgs) as the main delegate:

 ref class EventReceiver { public: void Handler(Object^ sender, MyEventArgs^ e) { } }; myEventSource->MyEvent += gcnew EventHandler<MyEventArgs^>(this, &EventReceiver::DataReceived); 
+12
source share

The syntax for C ++ / CLI is:

 delegate void MyOwnEventHandler(Object^ sender, Eventargs^ e) { } 

To register this event:

 objectPtr->MyEvent += gcnew EventHandler(MyOwnEventHandler); 
+6
source share

All Articles