You must install the event handlers you write to be able to use them in your application. Installing the event handler involves three steps.
If you read the introduction, you may remember that Carbon events have four types of targets: application, window, menu, and control. The event handler you write must be for one of these four targets. The usual choices are application and window. If you’re writing a fullscreen game, you’ll be writing application event handlers. Window event handlers are more common in applications where you’re doing a lot of work in windows, such as word processors, spreadsheets, board games, card games, and strategy games.
To specify the events you want to handle, create an array of type EventTypeSpec (or a variable if you want to handle only one event). The EventTypeSpec data structure has two components: an event class, and an event type. Common event classes include keyboard, mouse, text input, command (for menu selections), window, and application. The event type specifies the actual event. Some common mouse events include mouse movement, mouse button down, and scroll wheel movement. The following declaration:
EventTypeSpec keyboardHandlerEvents =
{ kEventClassKeyboard, kEventRawKeyDown };
Tells the handler to handle key down events, which occur when the user presses a key on the keyboard. Key down events are what you’re most interested in for game development.
To install an application event handler, call the function InstallApplicationEventHandler(). This function takes five arguments.
The following code provides an example of installing an application event handler in C++:
void GameApp::InstallKeyboardEventHandler(void)
{
EventTypeSpec keyboardHandlerEvents =
{ kEventClassKeyboard, kEventRawKeyDown };
InstallApplicationEventHandler(NewEventHandlerUPP(KeyboardEventHandler),
1, &keyboardHandlerEvents, this, NULL);
}
If you want to install a window event handler, call the function InstallWindowEventHandler(). Its first argument is the window you want to attach the event handler to. The remaining arguments are the same as the arguments to InstallApplicationEventHandler(). The functions InstallMenuEventHandler() and InstallControlEventHandler() install menu and control event handlers respectively. They work similarly to InstallWindowEventHandler() but take a menu or a control as the first argument instead of a window.
Next (Writing the Event Handler)
Previous (Installing Standard Event Handlers)