Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

How to: Add Multiple Handlers to Events

An event receiver, or any other client code can add one or more handlers to an event.

Example

// mcppv2_events4.cpp
// compile with: /clr
using namespace System;
#include <stdio.h>

delegate void ClickEventHandler(int, double);
delegate void DblClickEventHandler(String^);

ref class EventSource {
public:
   event ClickEventHandler^ OnClick;
   event DblClickEventHandler^ OnDblClick;

   void FireEvents() {
      OnClick(7, 3.14159);
      OnDblClick("Started");
   }
};

ref struct EventReceiver {
public:
   void Handler1(int x, double y) {
      System::Console::Write("Click(x={0},y={1})\n", x, y);
   };

   void Handler2(String^ s) {
      System::Console::Write("DblClick(s={0})\n", s->ToCharArray());
   }

   void Handler3(String^ s) {
      System::Console::WriteLine("DblClickAgain(s={0})\n", s->ToCharArray());
   }

   void AddHandlers(EventSource^ pES) {
      pES->OnClick += 
         gcnew ClickEventHandler(this,&EventReceiver::Handler1);
      pES->OnDblClick += 
         gcnew DblClickEventHandler(this,&EventReceiver::Handler2);
      pES->OnDblClick += 
         gcnew DblClickEventHandler(this, &EventReceiver::Handler3);
   }

   void RemoveHandlers(EventSource^ pES) {
      pES->OnClick -= 
         gcnew ClickEventHandler(this, &EventReceiver::Handler1);
      pES->OnDblClick -= 
         gcnew DblClickEventHandler(this, &EventReceiver::Handler2);
      pES->OnDblClick -= 
         gcnew DblClickEventHandler(this, &EventReceiver::Handler3);
   }
};

int main() {
   EventSource^ pES = gcnew EventSource;
   EventReceiver^ pER = gcnew EventReceiver;

   // add handlers
   pER->AddHandlers(pES);
   
   pES->FireEvents();

   // remove handlers
   pER->RemoveHandlers(pES);
}

Output

Click(x=7,y=3.14159)
DblClick(s=System.Char[])
DblClickAgain(s=System.Char[])

See Also

Community Additions

ADD
Show:
© 2015 Microsoft