Identifying Multiple Event Sources From A Single Callback

From CEGUI Wiki - Crazy Eddie's GUI System (Open Source)
Revision as of 11:20, 28 February 2011 by Capek (Talk | contribs) (Lets use <source> instead of <syntaxhighlight>, it is much less typo-prone)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Sometimes you would like to identify the sender of an event from within your callback function. For example, you would like to execute some common code for your buttons, like triggering a sound to be played on CEGUI::PushButton::EventClicked. Here is an example CEGUI::PushButton we would like to wire up:

CEGUI::PushButton* pushButton = 
  static_cast<CEGUI::PushButton*>
    (CEGUI::WindowManager::getSingleton().createWindow("WindowsLook/Button", "TheButton"));
 
pushButton->subscribeEvent(CEGUI::PushButton::EventClicked,
                           CEGUI::Event::Subscriber(&MainMenu::OnButtonClick, this));

To do this, simply cast the CEGUI::EventArgs in your callback to a CEGUI::WindowEventArgs. The CEGUI::WindowEventArgs object contains a pointer to the CEGUI::Window that sent the event. Now its as easy as calling CEGUI::Window::getName(). Obviously, you can do much more now that you have a pointer to the window who fired the event, but this is just an example:

bool MainMenu::OnButtonClick(const CEGUI::EventArgs& e)
{
  const CEGUI::MouseEventArgs& we = 
    static_cast<const CEGUI::MouseEventArgs&>(e);
 
  CEGUI::String senderID = we.window->getName();
 
  if (senderID == "TheButton")
  {
    // code for dealing with a "TheButton"
  }
 
  return true;
}