O'Reilly logo

Beginning Mac OS® X Programming by Drew McCormack, Michael Trent

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required