How to: Define Event Accessor Methods
The following sample shows how you can define an event's behavior when handlers are added or removed, and for when an event is raised.
Example
Code
// mcppv2_events6.cpp
// compile with: /clr
using namespace System;
public delegate void MyDel();
public delegate int MyDel2(int, float);
ref class EventSource {
public:
MyDel ^ pE;
MyDel2 ^ pE2;
event MyDel^ E {
void add(MyDel^ p) {
pE = static_cast<MyDel^> (Delegate::Combine(pE, p));
// cannot refer directly to the event
// E = static_cast<MyDel^> (Delegate::Combine(pE, p)); // error
}
void remove(MyDel^ p) {
pE = static_cast<MyDel^> (Delegate::Remove(pE, p));
}
void raise() {
if (pE != nullptr)
pE->Invoke();
}
} // E event block
event MyDel2^ E2 {
void add(MyDel2^ p2) {
pE2 = static_cast<MyDel2^> (Delegate::Combine(pE2, p2));
}
void remove(MyDel2^ p2) {
pE2 = static_cast<MyDel2^> (Delegate::Remove(pE2, p2));
}
int raise(int i, float f) {
if (pE2 != nullptr) {
return pE2->Invoke(i, f);
}
return 1;
}
} // E2 event block
};
public ref struct EventReceiver {
void H1() {
Console::WriteLine("In event handler H1");
}
int H2(int i, float f) {
Console::WriteLine("In event handler H2 with args {0} and {1}", i.ToString(), f.ToString());
return 0;
}
};
int main() {
EventSource ^ pE = gcnew EventSource;
EventReceiver ^ pR = gcnew EventReceiver;
// hook event handlers
pE->E += gcnew MyDel(pR, &EventReceiver::H1);
pE->E2 += gcnew MyDel2(pR, &EventReceiver::H2);
// raise events
pE->E();
pE->E2::raise(1, 2.2); // call event through scope path
// unhook event handlers
pE->E -= gcnew MyDel(pR, &EventReceiver::H1);
pE->E2 -= gcnew MyDel2(pR, &EventReceiver::H2);
// raise events, but no handlers
pE->E();
pE->E2::raise(1, 2.5);
}
Output
In event handler H1 In event handler H2 with args 1 and 2.2