TweetFollow Us on Twitter

Sep 98 Getting Started

Volume Number: 14 (1998)
Issue Number: 9
Column Tag: Getting Started

Apple Events

by Dave Mark and Dan Parks Sydow

How a Mac program handles Apple events

An Apple event is a high-level event that allows a program to communicate with another program, with the Finder, or even with itself. The program that issues the Apple event is referred to as the client application, while the program that receives and responds to the event is called the server application. Apple events are especially important when the Finder needs to communicate with a program. For instance, when the user opens a document by dragging its icon onto the icon of the application that created it, an Apple event is involved. In such a case the Finder launches the application (if it's not already running) and then sends an Open Document Apple event to the program to tell the program to open the dragged document. In this type of communication the Finder is the client and the application is the server. This month, we'll look at how Apple events make this type of common and important Finder-application communication possible. And, of course, we'll look at how you can incorporate this behavior into your own Mac applications.

The Required Apple Events

In the very old days (we're talking pre-System 7 here), when a user double-clicked on a document the Finder first looked up the document's creator and type in its desktop database to figure out which application to launch. It then packaged information about the document (or set of documents if the user double-clicked on more than one) in a data structure, launched the appropriate application, and passed the data structure to the application. To access this data structure, the application called the routine CountAppFiles() (to find out how many documents it needs to open or print) then, for each one, it called GetAppFiles() (to get the information necessary to open the file) and either opened or printed the file. This model is no longer supported -- it's been out of date for quite a while. In System 7, and now Mac OS 8, when a user opens a document the Finder still uses the file's creator and type to locate the right application to launch. Once the application is launched, however, things differ. Now, the Finder sends the program a series of Apple events.

  • If the application was launched by itself, with no documents, the Finder sends it an Open Application Apple event. This tells the application to do its standard initialization and assume that no documents were opened. In response to an Open Application Apple event, the application will usually (but not necessarily) create a new, untitled document.
  • If a document or set of documents were used to launch the application, the Finder packages descriptions of the documents in a data structure known as a descriptor, adds the descriptor to an Open Document Apple event, then sends the event to the application. When the application gets an Open Document event, it pulls the list of documents from the event and opens each document.
  • If the user asked the Finder to print, rather than open, a document or set of documents, the Finder sends a Print Document Apple event instead of an Open Document event. The same descriptor procedure as used for an Open Document Apple event is followed, but in response to a Print Document Apple event the application prints rather than opens the document.
  • Finally, if the Finder wants an application to quit (perhaps the user selected Shut Down from the Special menu) it sends the application a Quit Application Apple event. When the application gets a Quit Application event, it does whatever housekeeping it needs to do in preparation for quitting, then sets the global flag that allows it to drop out of the main event loop and exit.

These events are the four required Apple events. As the name implies, your application is expected to handle these events. For brevity, and to isolate individual programming topics, previous Getting Started examples didn't include Apple event code. To be considered a user-friendly, well-behaved program, your full-featured Mac application must handle these events.

There are a couple of other situations besides the above-mentioned scenarios where your application might receive one of the required Apple events. For starters, any application can package and send an Apple event. If you own a copy of CE Software's QuicKeys, you've got everything you need to build and send Apple events. If you have the AppleScript extension installed on your Mac, you can use Apple's Script Editor application to write scripts that get translated into Apple events. If you make your application recordable (so that the user can record your application's actions using the Script Editor, or any other Apple event recording application) you'll wrap all of your program's actions in individual Apple events. This means that when the user selects Open from the File menu, you'll send yourself an Open Document Apple event. If the user quits, you'll send yourself a Quit Application event.

In addition to the events described above, there are other situations in which the Finder will send you one of the four required Apple events. If the user double-clicks on (or otherwise opens) one of your application's documents, the Finder will package the document in an Open Document Apple event and send the event to your application. The same is true for the Print Document Apple event.

The user can also drag a document onto your application's icon. If your application is set up to handle that type of document, your application's icon will invert and, when the user releases the mouse button, the Finder will embed the document in an Open Document Apple event and send the event to your application. Note that this technique can be used to launch your application or to request that your application open a document once it is already running.

Apple Event Handlers

Apple events are placed in an event queue, much like the events you already know, love, and process, such as mouseDown, activateEvt, and updateEvt. So far, the events you've been handling have all been low-level events -- the direct result of a user's actions. The user uncovers a portion of a window, an updateEvt is generated. The user clicks the mouse button, a mouseDown is generated. Apple events, on the other hand, are known as high-level events -- the result of interprocess communication instead of user-process communication. As you process events retrieved by WaitNextEvent(), you'll take action based on the value in the event's what field. If the what field contains the constant updateEvt, you'll call your update handling routine, etc. If the what field contains the constant kHighLevelEvent, you'll pass the event to the routine AEProcessAppleEvent(). Here's a typical event-handling routine that supports Apple events:

void   DoEvent( EventRecord *eventPtr )
{
   char      theChar;

   switch ( eventPtr->what )
   {
      case mouseDown: 
         HandleMouseDown( eventPtr );
         break;
      case keyDown:
      case autoKey:
         theChar = eventPtr->message & charCodeMask;
         if ( (eventPtr->modifiers & cmdKey) != 0 ) 
            HandleMenuChoice( MenuKey( theChar ) );
         break;
      case updateEvt:
         DoUpdate( eventPtr );
         break;
      case kHighLevelEvent:
         AEProcessAppleEvent( eventPtr );
         break;
   }
}

AEProcessAppleEvent() is a powerful routine whose purpose is to identify the type of Apple event that is to be processed, and to begin processing that event by passing the event to an Apple event handler. An Apple event handler is a routine you've written specifically to handle one type of Apple event. If your program supports the four required Apple event types, you'll be writing four Apple event handler routines. This month's example program provides an example of each of these handlers.

Writing an Apple event handler isn't enough -- you also need to install it. You install a handler by passing its address (in the form of a universal procedure pointer, or UPP) to the Toolbox routine AEInstallEventHandler(). This installation takes place early in your program -- typically just after Toolbox initialization and the setting up of your program's menu bar. Once the handlers are installed, your work is done -- when your program receives an Apple event the call to AEProcessAppleEvent() automatically calls the appropriate handler.

AEHandler

This month's example program, AEHandler, can be launched like any other Mac application: by double-clicking on its icon. When launched in this way the program does nothing more than display an empty window. AEHandler can also be launched by dragging and dropping an AEHandler file onto the application icon. Using this second program-starting method opens the dropped file. Dragging and dropping a file on the application icon of the already-running AEHandler program also results in the file being opened. And unlike a program that doesn't support the required Apple events, AEHandler knows how to quit itself when Shut Down is selected from the desktop's Special menu.

When you run AEHandler you'll note that there's not much to see. For the example program we aren't interested in a fancy interface, though -- so you aren't getting shortchanged. What AEHandler is doing behind the scenes is far more interesting: Apple events are responsible for all above-mentioned features. This month's program, then, serves as a skeleton you can use to add the required Apple events to your own programs.

Creating the AEHandler Resources

Start off by creating a folder called AEHandler in your development folder. Launch ResEdit and create a new file called AEHandler.rsrc in the AEHandler folder. Create the menu-related resources -- by now you should be used to creating menu bar and menu resources. The MBAR resource has an ID of 128, and it references the three MENU resources shown in Figure 1.


Figure 1. The three MENUs used by AEHandler.

Now create a WIND resource with an ID of 128. The coordinates of the window aren't critical -- we used a top of 50, a left of 10, a bottom of 100, and a right of 310. Use the standard document proc (leftmost in a ResEdit editing pane).

The AEHandler program includes some error-checking code. Should a problem arise, the program posts an alert that holds a message descriptive of the problem. This alert is defined by an ALRT with an ID of 128, a top of 40, left of 40, bottom of 155, and right of 335. Next, create a corresponding DITL with an ID of 128 and two items. Item 1 is an OK button with a top of 85, a left of 220, a bottom of 105, and a right of 280. Item 2 is a static text item just like the one shown in Figure 2. Make sure to include the caret and zero characters in the Text field.


Figure 2. The static text item for the error alert.

That covers the standard resources. Next come the resources that link specific document types to our application and that tie a set of small and large icons to our application. The Finder uses these resources to display an icon that represents our application in different situations (a large icon when the app is on the desktop, a small icon to display in the right-most corner of the menu bar when our app is front-most). The Finder uses the non-icon resources to update its desktop database.

Create a new BNDL resource with a resource ID of 128. When the BNDL editing window appears in ResEdit, select Extended View from the BNDL menu. This gives you access to some additional fields. Put your application's four-byte signature in the Signature field. Every time you create a new application, you'll have to come up with a four-character string unique to your application. To verify that the signature is unique, you'll need to send it to Apple at their Creator/File Type Registration web site http://developer.apple.com/dev/cftype/. If you don't have a signature handy, and don't feel like going online to find an unused one to register, feel free to temporarily use one of ours for now. The signature 'DMDS' is one we've registered, but don't (and won't) use for any distributed application -- so you won't run into any conflicts with other programs on your Mac.

Now fill in the remaining two fields near the top of the BNDL resource. As shown in Figure 3, the ID is set to 0 and the © String field holds a copyright string that will appear in the Finder's Get Info window for your application.

Figure 3. The AEHandler BNDL resource.

Finish off the BNDL resource by adding information about each type of file that the Finder should associate with the AEHandler program. Select New File Type from the Resource menu. Use the specifications in Figure 3 to fill out the information for the APPL file type. This ties the first row of icons to the application itself. To edit the icons, double-click on the icon area and ResEdit will open an icon family editing window.

Back in the BNDL editing window, select New File Type again to add a second row of file types to the BNDL window. This time use the specs in Figure 3 to fill out the info for files of type TEXT. By doing this, we've told the finder that files with the signature 'DMDS' and of type 'TEXT' belong to the application AEHandler. Once again, double-click on the icon family to edit the individual icons.

If your application will support file types belonging to other applications, create file type entries in the BNDL resource for them as well, but don't edit the icons -- leave them blank.

Finally, be aware that the Finder uses the file type entries to determine what files can drop launch your application. Right now, the Finder will only let you drop-launch files with the signature 'DMDS' and of type 'TEXT' on AEHandler. To make AEHandler respond to all file types, create a new file type entry with the file type '****'. Don't edit the icons -- leave them blank.

That's it for the AEHandler.rsrc file -- but not for ResEdit. Save your changes to AEHandler.rsrc and close the resource file. While still in ResEdit, create a new resource file called test.text. Select Get Info for test.text from ResEdit's File menu. When the info window appears, set the file's type to TEXT and its creator to whatever signature you used (if you used ours, it's DMDS). That's it. Save your changes, quit ResEdit, and get set to create the project.

Creating the AEHandler Project

Launch CodeWarrior and create a new project based on the MacOS:C_C++:MacOS Toolbox:MacOS Toolbox Multi-Target stationary. Uncheck the Create Folder check box. Name the project AEHandler.mcp and specify that the project be placed in the AEHandler folder. Immediately edit the creator information in the target panel of the project settings dialog box (select the project settings item from the Edit menu, click on 68K Target or PPC Target in the scrollable list, and then type the four-character creator code in the Creator edit box). Set the project's creator to the creator you used ('DMDS' if you've followed our suggestion). Next, be sure that the isHighLevelEventAware flag is set in the 'SIZE' Flags popup menu. By default it should be. If it isn't, select it -- if it's not set, the Apple Event Manager won't call your handlers!

Remove the SillyBalls.c and SillyBalls.rsrc files from, and add the AEHandler.rsrc file to, the project. This project doesn't make use of any of the standard ANSI libraries, so feel free to clean up the project window by removing the ANSI Libraries folder.

Next, choose New from the File menu to create a new source code window. Save it with the name AEHandler.c, then add the new file to the project by choosing Add Window from the Project menu. The entire AEHandler source code listing can be found in the source code walk-through. You can type it into the AEHandler.c file as you read the walk-through, or you can save a lot of effort by just downloading the whole project from MacTech's ftp site ftp://ftp.mactech.com/src/mactech/volume14_1998/14.09.sit.

Walking Through the Source Code

The AEHandler source code listing begins with a number of #defines -- most of which you'll be familiar with from previous examples.

/********************* constants *********************/

#define kBaseResID         128
#define kALRTResID         128
#define kWINDResID         128

#define kSleep            7
#define kMoveToFront      (WindowPtr)-1L
#define kGestaltMask      1L
#define kActivate         false
#define kVisible          true

#define kWindowStartX      20
#define kWindowStartY      50

#define mApple             kBaseResID
#define iAbout             1

#define mFile              kBaseResID+1
#define iClose             1
#define iQuit              3

As always, the global variable gDone indicates when it's time to exit the main event loop. Variables gNewWindowX and gNewWindowY serve as offsets to stagger open windows. And of course each application-defined function has its own prototype.

/********************** globals **********************/

Boolean      gDone;
short        gNewWindowX = kWindowStartX,
             gNewWindowY = kWindowStartY;

/********************* functions *********************/

void               ToolBoxInit( void );
void               MenuBarInit( void );
void               AEInit( void );
void               AEInstallHandlers( void );
pascal   OSErr   DoOpenApp(   AppleEvent *event, AppleEvent *reply, 
                                 long refcon );
pascal   OSErr   DoOpenDoc(   AppleEvent *event, AppleEvent *reply, 
                                 long refcon );
pascal   OSErr   DoPrintDoc(AppleEvent *event, AppleEvent *reply, 
                                 long refcon );
pascal   OSErr   DoQuitApp( AppleEvent *event, AppleEvent *reply, 
                                 long refcon );
void               OpenDocument( FSSpec *fileSpecPtr );
WindowPtr      CreateWindow( Str255 name );
void               DoError( Str255 errorString );
void               EventLoop( void );
void               DoEvent( EventRecord *eventPtr );
void               HandleMouseDown( EventRecord *eventPtr );
void               HandleMenuChoice( long menuChoice );
void               HandleAppleChoice( short item );
void               HandleFileChoice( short item );
void               DoUpdate( EventRecord *eventPtr );
void               DoCloseWindow( WindowPtr window );

The main() routine does its usual work, but here it also initializes Apple events before entering the main event loop.

/************************ main ***********************/

void   main( void )
{
   ToolboxInit();
   MenuBarInit();
   AEInit();
   
   EventLoop();
}

/******************** ToolBoxInit ********************/

void   ToolboxInit( void )
{
   InitGraf( &qd.thePort );
   InitFonts();
   InitWindows();
   InitMenus();
   TEInit();
   InitDialogs( 0L );
   InitCursor();
}

/******************** MenuBarInit ********************/

void   MenuBarInit( void )
{
   Handle            menuBar;
   MenuHandle      menu;
   
   menuBar = GetNewMBar( kBaseResID );
   SetMenuBar( menuBar );

   menu = GetMenuHandle( mApple );
   AddResMenu( menu, 'DRVR' );
   
   DrawMenuBar();
}

The Apple-defined constant gestaltAppleEventsAttr is a selector code that tells the Toolbox function Gestalt() to return information about the availability of Apple events on the user's machine. If Gestalt() fills feature with the Apple-defined constant gestaltAppleEventsPresent, then we know it's okay to include Apple event code in our program. If there's an error along the way, we call our own DoError() routine (discussed later) to clue the user in to the problem. AEInit() ends with a call to AEInstallHandler(), which is described next.

/********************** AEInit ***********************/

void   AEInit( void )
{
   OSErr   err;
   long      feature;
   
   err = Gestalt( gestaltAppleEventsAttr, &feature );
   if ( err != noErr )
      DoError( "\pError returned by Gestalt!" );
      
   if ( !( feature & ( kGestaltMask << 
                                    gestaltAppleEventsPresent ) ) )
      DoError( "\pThis Mac does not support Apple events..." );
   
   AEInstallHandlers();
}

Each Apple event handler needs to be installed. Looking at how that is done for one handler provides you with enough information to see how any handler is installed. Let's look at how our AEInstallHandlers() function installs the handler routine that's to process Open Application Apple events.

A call to the Toolbox routine AEInstallEventHandler() is made to specify that the application-defined routine DoOpenApp() (covered ahead) is the handler for Open Application events. The first argument to AEInstallEventHandler(), kCoreEventClass, defines the event class of the event to be handled. All four of the required Apple events are considered core events. The second argument, kAEOpenApplication, is an Apple-defined event ID that specifies which particular Apple event is to be handled. The third argument is a pointer to the application-defined function that is to handle this one type of Apple event. When passed a function name, the Toolbox function NewAEEventHandlerProc() returns the needed pointer. The fourth argument, 0L, is a reference value that the Apple Event Manager uses each time it invokes the event handler function. You can safely us a value of 0 here. The final argument is a Boolean value that specifies in which Apple event dispatch table (the means of correlating an Apple event with a handler) the handler should be added. A value of false here tells the Apple Event Manager to add the event handler to the application's own dispatch table as opposed to adding it to the system dispatch table (a table that holds handlers available to all applications). Should the call to AEInstallEventHandler() fail for any reason, we call our DoError() routine (discussed ahead), specifying which Apple event type was the source of the failure.

/***************** AEInstallHandlers *****************/

void   AEInstallHandlers( void )
{
   OSErr            err;
   
   err = AEInstallEventHandler( kCoreEventClass, 
               kAEOpenApplication, 
               NewAEEventHandlerProc( DoOpenApp ), 0L, false );
   if ( err != noErr )
      DoError( "\pError installing Open App handler..." );
   
   err = AEInstallEventHandler( kCoreEventClass, 
               kAEOpenDocuments,
               NewAEEventHandlerProc( DoOpenDoc ), 0L, false );
   if ( err != noErr )
      DoError( "\pError installing Open Doc handler..." );
      
   err = AEInstallEventHandler( kCoreEventClass, 
               kAEPrintDocuments,
               NewAEEventHandlerProc( DoPrintDoc ), 0L, false );
   if ( err != noErr )
      DoError( "\pError installing Print Doc handler..." );
      
   err = AEInstallEventHandler( kCoreEventClass, 
               kAEQuitApplication,
               NewAEEventHandlerProc( DoQuitApp ), 0L, false );
   if ( err != noErr )
      DoError( "\pError installing Quit App handler..." );
}

An Apple event handler has a clearly defined purpose. It extracts data from the Apple event, handles the specific action that the event requests, and returns an error result code to indicate whether or not the event was successfully handled. How the functionality of the event handler routine is implemented is up to you. Each handler has the same general format: it starts with the pascal keyword, has a return type of OSErr, and includes three parameters. The first parameter holds the Apple event to handle. The second parameter is available to hold information that might need to be returned to AEProcessAppleEvent() (recall that this is the routine that invokes the handler). The final parameter is a reference value that your application will typically ignore. DoOpenApp(), which is the event handler for an Open Application Apple event, provides an example:

/******************* DoOpenApp ***********************/

pascal OSErr   DoOpenApp(   AppleEvent *event, AppleEvent *reply, 
                                 long refcon )
{
   OpenDocument( nil );
   
   return noErr;
}

DoOpenApp() is invoked when the AEHandler application is launched. We've opted to have the program open a new window at startup. The application-defined routine OpenDocument() takes care of that task. Later we mention how OpenDocument() works, but there's no need to get into the nitty-gritty. The point has been made: the body of an event handler simply holds the typical Mac code that is needed to solve the task at hand. Once you know the format of an event handler, writing the routine itself is no different than writing any other function.

Some event handlers are easier to write than others. Consider our example program's handler for a Print Document Apple event:

/****************** DoPrintDoc ***********************/

pascal OSErr   DoPrintDoc(AppleEvent *event, AppleEvent *reply, 
                                 long refcon )
{
   return noErr;
}

The AEHandler program doesn't support printing, so we've defined the DoPrintDoc() function to do nothing more than return. So while the program technically does handle a Print Document Apple event, the effect is that the event is ignored. Before you cry "foul!", keep in mind that we haven't discussed the topic of printing in Getting Started -- so we really can't venture off down that road just yet. At least now our application can be considered set up and ready to respond to printing requests from the Finder. Should we get into printing in the future (and if demand warrants it, of course we will), we can add the printing code in the DoPrintDoc() routine.

A Quit Application Apple event is simple to handle -- all we need to do is set the global variable gDone to true. The AEHandler version of this handler also beeps to let you know that it was an Apple event rather than the Quit menu item that caused the application to quit -- your application's version of this handler won't need the call to SysBeep().

/******************* DoQuitApp ***********************/

pascal OSErr   DoQuitApp(   AppleEvent *event, AppleEvent *reply, 
                                 long refcon )
{
   SysBeep( 10 );
   gDone = true;
   
   return noErr;
}

Finally, it's on to a handler that has a little substance to it. If the user drops an AEHandler file onto the AEHandler icon in the Finder, then the AEHandler application receives an Open Document Apple event. Some Apple events are composed of parameters -- records which contain information to be used by the receiving application. An event's direct parameter is the one that the receiving application is to act upon. For the Open Document event, the direct parameter is a descriptor list of the files that are to be opened. A call to AEGetParamDesc() delivers that list to the handler. Here we're saving the list to the local variable docList:

err = AEGetParamDesc( event, keyDirectObject, typeAEList, 
                              &docList);

Next, we determine the number of entries in the list so that we know how many files are to be opened:

err = AECountItems( &docList, &numDocs );

A for loop opens each file in turn. A call to AEGetNthPtr() returns one item from the list. We do a little finagling to make sure that the returned item is received in the form of a file system specification, or FSSpec. The application-defined routine OpenDocument() does the actual opening of the file.

for ( i=1; i<=numDocs; i++ )
{
   err = AEGetNthPtr( &docList, i, typeFSS, &keywd, 
                            &returnedType, (Ptr)&fileSpec,
                            sizeof( fileSpec ), &actualSize );

   OpenDocument( &fileSpec );
}

Calling AEGetParamDesc() resulted in the Apple Event Manager creating a copy of the descriptor list for the program's use. We're done with that copy, so we'll deallocate the memory it occupied:

err = AEDisposeDesc( &docList );

We've just covered it piecemeal, now here's the DoOpenDoc() function in its entirety:

/******************* DoOpenDoc ***********************/

pascal OSErr   DoOpenDoc(   AppleEvent *event, AppleEvent *reply, 
                                 long refcon )
{
   OSErr       err;
   FSSpec      fileSpec;
   long        i, numDocs;
   DescType    returnedType;
   AEKeyword   keywd;
   Size        actualSize;
   AEDescList   docList = { typeNull, nil };

   err = AEGetParamDesc( event, keyDirectObject,
                     typeAEList, &docList);

   err = AECountItems( &docList, &numDocs );
   
   for ( i=1; i<=numDocs; i++ )
   {
      err = AEGetNthPtr( &docList, i, typeFSS, &keywd,
                     &returnedType, (Ptr)&fileSpec,
                     sizeof( fileSpec ), &actualSize );

      OpenDocument( &fileSpec );
   }

   err = AEDisposeDesc( &docList );

   return   err;
}

OpenDocument() selects an appropriate title for the about-to-be-opened window, then calls the application-defined routine CreateWindow() to actually create and display the new window.

/***************** OpenDocument **********************/

void   OpenDocument( FSSpec *fileSpecPtr )
{
   WindowPtr   window;
   
   if ( fileSpecPtr == nil )
      window = CreateWindow( "\p<Untitled>" );
   else
      window = CreateWindow( fileSpecPtr->name );
}

CreateWindow() opens a new window based on AEHandler's one WIND resource, sets the window's title, then offsets the window from the last-opened window. The bulk of CreateWindow() is code for staggering the new window. The newly opened window will be empty -- regardless of the contents of the file that's being opened. The code necessary to read the contents of the file and then display that information in a window is dependent on what your application does.

/***************** CreateWindow **********************/

WindowPtr   CreateWindow( Str255 name )
{
   WindowPtr   window;
   short         windowWidth, windowHeight;
   
   window = GetNewWindow( kWINDResID, nil, kMoveToFront );
   
   SetWTitle( window, name );
   
   MoveWindow( window, gNewWindowX, gNewWindowY, kActivate );
   
   gNewWindowX += 20;
   windowWidth = window->portRect.right - 
                              window->portRect.left;
   
   if ( gNewWindowX + windowWidth > 
               qd.screenBits.bounds.right )
   {
      gNewWindowX = kWindowStartX;
      gNewWindowY = kWindowStartY;
   }
      
   gNewWindowY += 20;
   windowHeight = window->portRect.bottom - 
                              window->portRect.top;
   
   if ( gNewWindowY + windowHeight > 
               qd.screenBits.bounds.bottom )
   {
      gNewWindowX = kWindowStartX;
      gNewWindowY = kWindowStartY;
   }
   
   ShowWindow( window );
   SetPort( window );
   
   return window;
}

If AEHandler encounters an error, it posts an alert that provides some error-specific information to help the user determine what went wrong. The DoError() routine displays this alert, then terminates the program. The Toolbox function ParamText() displays up to four strings in an alert -- the routine looks for occurrences of the strings "^0", "^1", "^2", and "^3" in any static text items in the frontmost alert or dialog box and replaces each with the four strings that were passed to ParamText(). In DoError() we only pass one string (the three "\p" values each representing empty strings) -- the string received in the errorString parameter to DoError(). Refer back to Figure 2 to see how this string will appear in the alert displayed by the subsequent call to StopAlert(). Including a DoError()-type routine in a program is a simple and effective way to handle errors -- consider incorporating such a function in any Mac program you write.

/********************* DoError ***********************/

void   DoError( Str255 errorString )
{
   ParamText( errorString, "\p", "\p", "\p" );
   
   StopAlert( kALRTResID, nil );
   
   ExitToShell();
}

The rest of the code takes care of event-handling, and should look quite familiar to you. That means we can dispense with the walk-through of it. Refer back to recent Getting Started columns for more information on event-handling.

/******************** EventLoop **********************/

void   EventLoop( void )
{      
   EventRecord      event;
   
   gDone = false;
   while ( gDone == false )
   {
      if ( WaitNextEvent( everyEvent, &event, kSleep, nil ) )
         DoEvent( &event );
   }
}

/********************* DoEvent ***********************/

void   DoEvent( EventRecord *eventPtr )
{
   char      theChar;
   
   switch ( eventPtr->what )
   {
      case mouseDown: 
         HandleMouseDown( eventPtr );
         break;
      case keyDown:
      case autoKey:
         theChar = eventPtr->message & charCodeMask;
         if ( (eventPtr->modifiers & cmdKey) != 0 ) 
            HandleMenuChoice( MenuKey( theChar ) );
         break;
      case updateEvt:
         DoUpdate( eventPtr );
         break;
      case kHighLevelEvent:
         AEProcessAppleEvent( eventPtr );
         break;
   }
}

/***************** HandleMouseDown *******************/

void   HandleMouseDown( EventRecord *eventPtr )
{
   WindowPtr   window;
   short         thePart;
   long            menuChoice;
   thePart = FindWindow( eventPtr->where, &window );
   switch ( thePart )
   {
      case inMenuBar:
         menuChoice = MenuSelect( eventPtr->where );
         HandleMenuChoice( menuChoice );
         break;
      case inSysWindow : 
         SystemClick( eventPtr, window );
         break;
      case inGoAway:
         if ( TrackGoAway( window, eventPtr->where ) )
            DoCloseWindow( window );
         break;
      case inContent:
         SelectWindow( window );
         break;
      case inDrag : 
         DragWindow( window, eventPtr->where, 
                         &qd.screenBits.bounds );
         break;
   }
}

/***************** HandleMenuChoice ******************/

void   HandleMenuChoice( long menuChoice )
{
   short   menu;
   short   item;
   if ( menuChoice != 0 )
   {
      menu = HiWord( menuChoice );
      item = LoWord( menuChoice );
      switch ( menu )
      {
         case mApple:
            HandleAppleChoice( item );
            break;
         case mFile:
            HandleFileChoice( item );
            break;
      }
      HiliteMenu( 0 );
   }
}

/**************** HandleAppleChoice ******************/

void   HandleAppleChoice( short item )
{
   MenuHandle   appleMenu;
   Str255      accName;
   short      accNumber;
   switch ( item )
   {
      case iAbout:
         SysBeep( 20 );
         break;
      default:
         appleMenu = GetMHandle( mApple );
         GetItem( appleMenu, item, accName );
         accNumber = OpenDeskAcc( accName );
         break;
   }
}

/***************** HandleFileChoice ******************/

void   HandleFileChoice( short item )
{
   switch ( item )
   {
      case iClose:
         DoCloseWindow( FrontWindow() );
         break;
      case iQuit:
         gDone = true;
         break;
   }
}

/********************* DoUpdate **********************/

void   DoUpdate( EventRecord *eventPtr )
{
   WindowPtr   window;
   
   window = (WindowPtr)eventPtr->message;
   
   BeginUpdate(window);
   EndUpdate(window);
}

/****************** DoCloseWindow ********************/

void   DoCloseWindow( WindowPtr window )
{
   if ( window != nil )
      DisposeWindow( window );
}

Running AEHandler

Save your code, then choose Run from CodeWarrior's Project menu to build and then run the AEHandler application. An untitled window should appear. If it didn't, go back and check your SIZE resource to make sure the High-Level-Event Aware flag is set.

As you look through the code, you'll see that the untitled window is created by the Open Application handler. Now double click on the file test.text. A window titled test.text should appear. This window was created by the Open Documents handler.

With AEHandler still running, go into the Finder and select Shut Down from the Special menu. The Finder should bring AEHandler to the front and send it a Quit Application Apple event. Our Quit Application handler beeps once then sets gDone to true. When you quit normally (by choosing Quit from the AEHandler's File menu), you won't hear this beep.

Till Next Month

Become comfortable with the AEHandler code so you can have all your own Mac applications support at least the four required Apple events. Play around with the AEHandler code. Add error-handling code where appropriate (for instance, the Open Document handler can call AEDisposeDesc() in response to errors returned by calls to AEGetParamDesc(), AECountItems(), and AEGetNthPtr()). Add some code to the Open Document handler to open the specified file and display info about the file in its window (maybe the file's size). While you wait for the next column, read up on the Apple Event Manager in Inside Macintosh: Interapplication Communication. See you next month...

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

coconutBattery 3.9.14 - Displays info ab...
With coconutBattery you're always aware of your current battery health. It shows you live information about your battery such as how often it was charged and how is the current maximum capacity in... Read more
Keynote 13.2 - Apple's presentation...
Easily create gorgeous presentations with the all-new Keynote, featuring powerful yet easy-to-use tools and dazzling effects that will make you a very hard act to follow. The Theme Chooser lets you... Read more
Apple Pages 13.2 - Apple's word pro...
Apple Pages is a powerful word processor that gives you everything you need to create documents that look beautiful. And read beautifully. It lets you work seamlessly between Mac and iOS devices, and... Read more
Numbers 13.2 - Apple's spreadsheet...
With Apple Numbers, sophisticated spreadsheets are just the start. The whole sheet is your canvas. Just add dramatic interactive charts, tables, and images that paint a revealing picture of your data... Read more
Ableton Live 11.3.11 - Record music usin...
Ableton Live lets you create and record music on your Mac. Use digital instruments, pre-recorded sounds, and sampled loops to arrange, produce, and perform your music like never before. Ableton Live... Read more
Affinity Photo 2.2.0 - Digital editing f...
Affinity Photo - redefines the boundaries for professional photo editing software for the Mac. With a meticulous focus on workflow it offers sophisticated tools for enhancing, editing and retouching... Read more
SpamSieve 3.0 - Robust spam filter for m...
SpamSieve is a robust spam filter for major email clients that uses powerful Bayesian spam filtering. SpamSieve understands what your spam looks like in order to block it all, but also learns what... Read more
WhatsApp 2.2338.12 - Desktop client for...
WhatsApp is the desktop client for WhatsApp Messenger, a cross-platform mobile messaging app which allows you to exchange messages without having to pay for SMS. WhatsApp Messenger is available for... Read more
Fantastical 3.8.2 - Create calendar even...
Fantastical is the Mac calendar you'll actually enjoy using. Creating an event with Fantastical is quick, easy, and fun: Open Fantastical with a single click or keystroke Type in your event details... Read more
iShowU Instant 1.4.14 - Full-featured sc...
iShowU Instant gives you real-time screen recording like you've never seen before! It is the fastest, most feature-filled real-time screen capture tool from shinywhitebox yet. All of the features you... Read more

Latest Forum Discussions

See All

Square Enix commemorates one of its grea...
One of the most criminally underused properties in the Square Enix roster is undoubtedly Parasite Eve, a fantastic fusion of Resident Evil and Final Fantasy that deserved far more than two PlayStation One Games and a PSP follow-up. Now, however,... | Read more »
Resident Evil Village for iPhone 15 Pro...
During its TGS 2023 stream, Capcom showcased the Following upcoming ports revealed during the Apple iPhone 15 event. Capcom also announced pricing for the mobile (and macOS in the case of the former) ports of Resident Evil 4 Remake and Resident Evil... | Read more »
The iPhone 15 Episode – The TouchArcade...
After a 3 week hiatus The TouchArcade Show returns with another action-packed episode! Well, maybe not so much “action-packed" as it is “packed with talk about the iPhone 15 Pro". Eli, being in a time zone 3 hours ahead of me, as well as being smart... | Read more »
TouchArcade Game of the Week: ‘DERE Veng...
Developer Appsir Games have been putting out genre-defying titles on mobile (and other platforms) for a number of years now, and this week marks the release of their magnum opus DERE Vengeance which has been many years in the making. In fact, if the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for September 22nd, 2023. I’ve had a good night’s sleep, and though my body aches down to the last bit of sinew and meat, I’m at least thinking straight again. We’ve got a lot to look at... | Read more »
TGS 2023: Level-5 Celebrates 25 Years Wi...
Back when I first started covering the Tokyo Game Show for TouchArcade, prolific RPG producer Level-5 could always be counted on for a fairly big booth with a blend of mobile and console games on offer. At recent shows, the company’s presence has... | Read more »
TGS 2023: ‘Final Fantasy’ & ‘Dragon...
Square Enix usually has one of the bigger, more attention-grabbing booths at the Tokyo Game Show, and this year was no different in that sense. The line-ups to play pretty much anything there were among the lengthiest of the show, and there were... | Read more »
Valve Says To Not Expect a Faster Steam...
With the big 20% off discount for the Steam Deck available to celebrate Steam’s 20th anniversary, Valve had a good presence at TGS 2023 with interviews and more. | Read more »
‘Honkai Impact 3rd Part 2’ Revealed at T...
At TGS 2023, HoYoverse had a big presence with new trailers for the usual suspects, but I didn’t expect a big announcement for Honkai Impact 3rd (Free). | Read more »
‘Junkworld’ Is Out Now As This Week’s Ne...
Epic post-apocalyptic tower-defense experience Junkworld () from Ironhide Games is out now on Apple Arcade worldwide. We’ve been covering it for a while now, and even through its soft launches before, but it has returned as an Apple Arcade... | Read more »

Price Scanner via MacPrices.net

New low price: 13″ M2 MacBook Pro for $1049,...
Amazon has the Space Gray 13″ MacBook Pro with an Apple M2 CPU and 256GB of storage in stock and on sale today for $250 off MSRP. Their price is the lowest we’ve seen for this configuration from any... Read more
Apple AirPods 2 with USB-C now in stock and o...
Amazon has Apple’s 2023 AirPods Pro with USB-C now in stock and on sale for $199.99 including free shipping. Their price is $50 off MSRP, and it’s currently the lowest price available for new AirPods... Read more
New low prices: Apple’s 15″ M2 MacBook Airs w...
Amazon has 15″ MacBook Airs with M2 CPUs and 512GB of storage in stock and on sale for $1249 shipped. That’s $250 off Apple’s MSRP, and it’s the lowest price available for these M2-powered MacBook... Read more
New low price: Clearance 16″ Apple MacBook Pr...
B&H Photo has clearance 16″ M1 Max MacBook Pros, 10-core CPU/32-core GPU/1TB SSD/Space Gray or Silver, in stock today for $2399 including free 1-2 day delivery to most US addresses. Their price... Read more
Switch to Red Pocket Mobile and get a new iPh...
Red Pocket Mobile has new Apple iPhone 15 and 15 Pro models on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide service using all the major... Read more
Apple continues to offer a $350 discount on 2...
Apple has Studio Display models available in their Certified Refurbished store for up to $350 off MSRP. Each display comes with Apple’s one-year warranty, with new glass and a case, and ships free.... Read more
Apple’s 16-inch MacBook Pros with M2 Pro CPUs...
Amazon is offering a $250 discount on new Apple 16-inch M2 Pro MacBook Pros for a limited time. Their prices are currently the lowest available for these models from any Apple retailer: – 16″ MacBook... Read more
Closeout Sale: Apple Watch Ultra with Green A...
Adorama haș the Apple Watch Ultra with a Green Alpine Loop on clearance sale for $699 including free shipping. Their price is $100 off original MSRP, and it’s the lowest price we’ve seen for an Apple... Read more
Use this promo code at Verizon to take $150 o...
Verizon is offering a $150 discount on cellular-capable Apple Watch Series 9 and Ultra 2 models for a limited time. Use code WATCH150 at checkout to take advantage of this offer. The fine print: “Up... Read more
New low price: Apple’s 10th generation iPads...
B&H Photo has the 10th generation 64GB WiFi iPad (Blue and Silver colors) in stock and on sale for $379 for a limited time. B&H’s price is $70 off Apple’s MSRP, and it’s the lowest price... Read more

Jobs Board

Housekeeper, *Apple* Valley Villa - Cassia...
Apple Valley Villa, part of a 4-star senior living community, is hiring entry-level Full-Time Housekeepers to join our team! We will train you for this position and Read more
Housekeeper, *Apple* Valley Village - Cassi...
Apple Valley Village Health Care Center, a 4-star rated senior care campus, is hiring a Part-Time Housekeeper to join our team! We will train you for this position! Read more
Optometrist- *Apple* Valley, CA- Target Opt...
Optometrist- Apple Valley, CA- Target Optical Date: Sep 23, 2023 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 796045 At Target Read more
Senior *Apple* iOS CNO Developer (Onsite) -...
…Offense and Defense Experts (CODEX) is in need of smart, motivated and self-driven Apple iOS CNO Developers to join our team to solve real-time cyber challenges. Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.