A.9. Chapter 9

A.9.1. Exercise 1 solution

You can solve this problem either by reusing the existing MainEventHandler or by creating a new event handler. The solution that follows extends MainEventHandler.

  1. In Xcode, replace main.c's call to InstallWindowEventHandler with the following code:

    // Install the window event handler
        EventTypeSpec eventSpec[2] = {
            {kEventClassKeyboard, kEventRawKeyDown},
            {kEventClassCommand, kEventCommandProcess},
        };
        InstallWindowEventHandler(window,
                                  NewEventHandlerUPP(MainEventHandler),
                                  2,
                                  eventSpec,
                                  (void*)window,
                                  NULL);
  2. Replace the entire MainEventHandler with the following code:

    OSStatus MainEventHandler(EventHandlerCallRef handler, EventRef event, void *userData)
    {
        OSStatus result = eventNotHandledErr;
    
        UInt32 class = GetEventClass(event);
    
        if (class == kEventClassCommand) {
    HICommand command;
    
            // get the HICommand from the event
            GetEventParameter(event,
                              kEventParamDirectObject,
                              typeHICommand,
                              NULL,
                              sizeof(HICommand),
                              NULL,
                              &command);
    
            // if this is a compute event regenerate the result string
            if (command.commandID == kComputeResultCmd) {
                ComputeResult((WindowRef)userData);
                result = noErr;
            }
        }
    
        // if this is a keyboard event, forward the event first, and then
        // recompute the events
        else if (class == kEventClassKeyboard) {
            // forward the event
            result = CallNextEventHandler(handler, event);
    
            // if the event was handled correctly, compute the result
            if (result == noErr) {
                ComputeResult((WindowRef)userData);
            }
        }
    
        return result;
    }
  3. Save your changes to main.c ...

Get Beginning Mac OS® X Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.