Introduction
Microsoft introduced an events system in VC++ 7 using keywords (event_source
, event_receiver
, __event
, __raise
, __hook
, __unhook
), expanding the language with a great tool.
This cool feature is not provided in VC++ 6.0 language.
My code provides users of VC++ 6.0 (could be used in other C++ systems) a simple events system, made in VC++ 6.0 and STL, with a small amount of code needed
in order to use it.
Using the code
The first thing to do is define the events provider, the events list and a struct that contains the events arguments.
The code is something like this:
1. Defining the events argument's list struct (inherited from EventArgs
).
struct SourceEventArgs : EventArgs {
int nRetCode;
};
2. Declaring a class capable of "firing" the events (inherited from SourceEvents
).
class Source : public SourceEvents {
...
};
3. Construct the "events" map
class Source : public SourceEvents {
protected:
_BEGIN_EVENTS_HANDLER
_EVENT_HANDLER( Close )
_EVENT_HANDLER( Idle )
_END_EVENTS_HANDLER
...
4. Define methods to "fire" the events
class Source : public SourceEvents {
protected:
_BEGIN_EVENTS_HANDLER
_EVENT_HANDLER( Close )
_EVENT_HANDLER( Idle )
_END_EVENTS_HANDLER
void OnIdle();
int OnClose(int);
...
void Source::OnIdle() {
SourceEventArgs e;
e.nRetCode = 0;
_raise(Idle, &e); }
int Source::OnClose(int nRetCode) {
SourceEventArgs e;
e.nRetCode = nRetCode;
_raise(Idle, &e); return e.nRetCode;
}
Ok, now the we have the class Source
, it can launch Close
and Idle
events for any number of event listener.
And now we need a class capable of listening to the events generated.
The code is simple
class Target {
int m_code;
public:
Target(int i) : m_code(i) { }
void OnIdle(Source* pObj, SourceEventArgs* e) {
cout << "Target" << m_code <<
" el valor actual de e = " << e->nRetCode++;
cout << " " << pObj->Name() << endl;
}
void OnClose(Source* , SourceEventArgs* e) {
cout << "Target" << m_code <<
" el valor actual de e = "<< e->nRetCode << endl;
e->nRetCode = 4;
}
_DECLARE_HOOK_LIST( Source ) };
_BEGIN_HOOK_LIST(Source, Target, SourceEventArgs)
_HOOK(Idle , OnIdle ) _HOOK(Close, OnClose) _END_HOOK_LIST
The last step is joining the object to listening events.
Source s;
Target t(1);
t.JoinTo(&s);
s.Idle();
s.Close();
t.UnJoinTo(&s);
Remember that it is important to call the unjoin
method before erasing the objects
Comment
Ok this it's my first one article and I expect that be of great aid. Please let me know and good look.
Edit History
27 Nov 2002 - Initial Edit
3 Dec 2002 - updated downloads
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.