How to: Access Events in Interfaces
The accessibility of a raise method is never public and is protected by default. A raise method is private if the event is private, and virtual if the event is declared virtual. If an event is declared in a managed interface, only its add and remove methods can be implemented.
Example
Code
// mcppv2_events2.cpp
// compile with: /clr
using namespace System;
delegate void Del(int, float);
// interface with event and a function to invoke event
interface struct I {
public:
event Del ^ E;
void fire(int, float);
};
// class that implements interface event and function
ref class EventSource: public I {
public:
virtual event Del^ E;
virtual void fire(int i, float f) {
E(i, f);
}
};
// class that defines event handler
ref class EventReceiver {
public:
void Handler(int i , float f) {
Console::WriteLine("EventReceiver::Handler");
}
};
int main () {
I^ es = gcnew EventSource();
EventReceiver^ er = gcnew EventReceiver();
// hook handler to event
es->E += gcnew Del(er, &EventReceiver::Handler);
// call event
es -> fire(1, 3.14);
// unhook handler from event
es->E -= gcnew Del(er, &EventReceiver::Handler);
}
Output
EventReceiver::Handler