WEBINAR: On-demand webcast
This article presents an Event Manager class to route messages to CWnd derived classes. The concept of this class is based on the popular Publisher / Subscriber idea. Any class shall be able to publish an event to a CEventManager object (single instance). Any class that is CWnd derived shall be able to subscribe to the event. When an event is signalled by the Publisher, the event manager shall propagate the message to the subscribers in the order of subscription.
// CWinApp derived class header file. #include "EventManager.h" extern CEventManager m_evtManager; ... // CWinApp derived class source file. CEventManager m_evtManager;After this any class that wishes use the CEventManager needs to make sure that the CWinApp derived class' header file is included in that class first.
To publish an event declare the event id in the stdafx.h first as
// stdafx.h #define MSG_MYMESSAGE WM_USER+1Then call the following function in the publisher's constructor
// publisher's class constructor m_evtManager.PublishEvent(MSG_MYMESSAGE);
Likewise in the subscribers class constructor,
// publisher's class constructor m_evtManager.SubscribeEvent(this, MSG_MYMESSAGE);For the subscriber, we would need to declare a function to handle the event and create the message map as follows.
// message map ON_MESSAGE(MSG_MYMESSAGE, OnMyMessage)and the function shall be declared as follows
// afx messages afx_msg void OnMyMessage(WPARAM, LPARAM)In this fashion, we can have as many subscribers listening to a single event.
For a publisher to signal an event, use the following command,
// publisher m_evtManager.SignalEvent(MSG_MYMESSAGE,wparam,lparam);
The method described here might not be optimized and there are in fact other alternatives. But what the CEventManager class shall allow us to do is to experiment and control how messages might propagate throughout the application. Thus any improvements are always welcomed.
The demo project attached demonstrates how messages might be propagated throughout the application. The CMainFrame class shall broadcast the Window Moved event which shall be caught by the CView class who shall inturn signal the CDisplayDlg1 class.
DownloadsDownload demo project - 52 Kb
Download source - 2 Kb