How do I assign an event handler to an event in C++/CLI?
Solution 1
In c#, you do it with the +=
operator:
someObj.SomeEvent += new EventHandler(Blah_SomeEvent);
...
private void Blah_SomeEvent(object sender, EventArgs e)
{
}
More-than-a-year-later-edit
It has been a long time since I posted this answer and someone noticed me that maybe it was wrong. I really don't know why the OP marked my answer as the right one (maybe OP was looking for this rather than c++-cli syntax? Who knows now).
Anyway, in c++-cli it would be:
someObj->SomeEvent+= gcnew EventHandler(this, &Blah_SomeEvent);
Solution 2
1: If underlyng delgate of the event is a custom one you define yourself that is a class memeber (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 underlying delegate is a global handler and has the standard signature for .NET events (object + event args) (from DPD answer):
delegate void MyOwnEventHandler(Object^ sender, EventArgs^ e) { }
myEventSource->MyEvent += gcnew EventHandler(MyOwnEventHandler);
3: If the underlying delegate has the 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 (that takes a MyEventArgs args parameter) as the underlying delegate:
ref class EventReceiver {
public:
void Handler(Object^ sender, MyEventArgs^ e) { }
};
myEventSource->MyEvent += gcnew EventHandler<MyEventArgs^>(this, &EventReceiver::DataReceived);
Solution 3
The syntax for C++/CLI is :
delegate void MyOwnEventHandler(Object^ sender, Eventargs^ e)
{
}
to register this for an event:
objectPtr->MyEvent += gcnew EventHandler(MyOwnEventHandler);
Related videos on Youtube
Comments
-
lital maatuk about 2 years
How do I add "events" to an "event"/delegate? What is the syntax? Is it the same in C++/CLI and in C#?
-
Jaroslav Jandek over 13 yearsAdding events means creating new events. Adding event handlers means subscribing to events so when an event is fired, your assigned handler methods get executed.
-
-
PostMan over 13 yearsOh, I find the answers to simple questions are just an important. Helps when the next user searches for the same thing :)
-
Matías Fidemraizer over 13 yearsRight, we avoid redundancy. But you forgot that most RTFM users won't search before asking haha ;)
-
dacap about 11 yearsThis is not a correct answer if we look at the question title (C++/CLI is not C#).
-
Matías Fidemraizer about 11 years@dacap Maybe you should downvote the question. If I'm wrong that OP looked for C# syntax, it should be that the question was incorrectly asked. Who knows why OP checked my answer as the correct one. Anyway, it seems that the OP found it useful.