Event1.cpp
上传用户:sz0451
上传日期:2022-07-29
资源大小:256k
文件大小:2k
- // This is the main project file for VC++ application project
- // generated using an Application Wizard.
- #include "stdafx.h"
- #using <mscorlib.dll>
- using namespace System;
- // Delegates
- __delegate void FirstEventHandler(String*);
- __delegate void SecondEventHandler(String*);
- // Event source class
- __gc class EvtSrc
- {
- public:
- // Declare the events
- __event FirstEventHandler* OnFirstEvent;
- __event SecondEventHandler* OnSecondEvent;
- // Event raising functions
- void RaiseOne(String* pMsg)
- {
- OnFirstEvent(pMsg);
- }
- void RaiseTwo(String* pMsg)
- {
- OnSecondEvent(pMsg);
- }
- };
- // Event receiver class
- __gc class EvtRcv1
- {
- EvtSrc* theSource;
- public:
- EvtRcv1(EvtSrc* pSrc)
- {
- if (pSrc == 0)
- throw new ArgumentNullException("Must have event source");
- // Save the source
- theSource = pSrc;
- // Add our handlers
- theSource->OnFirstEvent +=
- new FirstEventHandler(this, &EvtRcv1::FirstEvent);
- theSource->OnSecondEvent +=
- new SecondEventHandler(this, &EvtRcv1::SecondEvent);
- }
- // Handler functions
- void FirstEvent(String* pMsg)
- {
- Console::WriteLine("EvtRcv1: event one, message was {0}",
- pMsg);
- }
- void SecondEvent(String* pMsg)
- {
- Console::WriteLine("EvtRcv1: event two, message was {0}",
- pMsg);
- }
- // Remove a handler
- void RemoveHandler()
- {
- // Remove the handler for the first event
- theSource->OnFirstEvent -= new FirstEventHandler(this, &EvtRcv1::FirstEvent);
- }
- };
- // This is the entry point for this application
- #ifdef _UNICODE
- int wmain(void)
- #else
- int main(void)
- #endif
- {
- Console::WriteLine(S"Event Example");
- // Create a source
- EvtSrc* pSrc = new EvtSrc();
- // Create a receiver, and bind it to the source
- EvtRcv1* pRcv = new EvtRcv1(pSrc);
- // Fire events
- Console::WriteLine("Fire both events:");
- pSrc->RaiseOne(S"Hello, mum!");
- pSrc->RaiseTwo(S"One big step");
- // Remove the handler for event one
- pRcv->RemoveHandler();
- // Fire events again
- Console::WriteLine("Fire both events again:");
- pSrc->RaiseOne(S"Hello, mum!");
- pSrc->RaiseTwo(S"One big step");
- return 0;
- }