How do I add "events" to an "event"/delegate? What is the syntax? Is it the same in C++/CLI and in C#?
To add an event handler to a dialog box control:Right-click the control for which you want to handle the notification event. On the shortcut menu, choose Add Event Handler to display the Event Handler Wizard. Select the event in the Message type box to add to the class selected in the Class list box.
C# supports event handler assignment using: The += operator, which is also used in the common language runtime (CLR) event handling model.
The most flexible way to set an event handler on an element is to use the EventTarget. addEventListener method. This approach allows multiple listeners to be assigned to an element, and for listeners to be removed if needed (using EventTarget.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With