[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.2.2 Event Handling

To make the testing somewhat easier we will add a way to terminate the application by responding to the ESC key. Add the following private methods to our class in `simple.h':

 
  static bool SimpleEventHandler (iEvent& ev);
  bool HandleEvent (iEvent& ev);

The static function SimpleEventHandler() will be registered to the event queue. It has to be a static function because the event queue expects to call a normal C-style function (alternatively you could also implement this by making a subclass of iEventHandler but this is more complicated and not really required).

HandleEvent() is the real event handler. SimpleEventHandler() only serves as a stub function to call HandleEvent().

Then add the following code before Simple::Initialize():

 
bool Simple::HandleEvent (iEvent& ev)
{
  if (ev.Type == csevKeyDown && ev.Key.Code == CSKEY_ESC)
  {
    csRef<iEventQueue> q (CS_QUERY_REGISTRY (object_reg, iEventQueue));
    if (q)
      q->GetEventOutlet()->Broadcast (cscmdQuit);
    return true;
  }
  return false;
}

bool Simple::SimpleEventHandler (iEvent& ev)
{
  return simple->HandleEvent (ev);
}

HandleEvent() checks if the ESC key has been pressed. If so it will use the object registry to find the global event queue object. Using Broadcast it will then broadcast the cscmdQuit message to all interested parties. This will cause the application to quit by ending the default run loop.

We also need to initialize this event handler function. To do that add the following after the call to csInitializer::RequestPlugins():

 
  if (!csInitializer::SetupEventHandler(
    object_reg, SimpleEventHandler))
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.simple",
	"Can't initialize event handler!");
    return false;
  }


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

This document was generated using texi2html