TweetFollow Us on Twitter

Rolling MDEF
Volume Number:10
Issue Number:6
Column Tag:Getting Started

Related Info: Menu Manager Custom Menus

Rolling Your Own MDEFs

Help your menus get the picture

By Dave Mark, MacTech Magazine Regular Contributing Author

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

This month’s program is a departure from our traditional applications. Though we do build an application, it only serves as a tester for our MENU definition procedure. When your application includes a menu bar made up of a series of MENU resources, you’ll normally take advantage of the standard menu definition procedure (better known as an MDEF) provided by the Menu Manager.

Every time you call MenuSelect() (in response to a command-key equivalent or to a click in the menu bar), the Menu Manager takes over, drawing and erasing menus in response to your mouse clicks. Every menu specifies an MDEF resource (we’ll get to that when we create the tester’s MENU resources later in the column). Each time a menu is drawn, the MDEF specified by the menu is called to draw the menu’s contents and to highlight the appropriate item as the mouse moves.

This month, we’re going to write our own MDEF, compile it into an MDEF resource, then write a test program to test the MDEF. Rather than rewrite the standard MDEF, our MDEF will create a menu of PICT resources, as opposed to text.

This MDEF is actually a rewrite of the MDEF from Volume II of the Mac Primer. Besides being a little long in the tooth (i.e., old and funky), the original broke some Toolbox rules that caused the Thought Police to pay me a visit...

Creating the MDEF Project

Create a folder called MDEF Files in your Development folder. Launch THINK C and create a new project named MDEF.Π. Add MacTraps to the project. Next, create a new source code file, save it as MDEF.c, and add it to the project.

Type in this source code in the MDEF.c window:

/* 1 */
#define kTopMargin 1
#define kLeftMargin2

void  DoSizeMessage( MenuHandle menu, Rect *menuRectPtr );
void  DoDrawMessage( MenuHandle menu, Rect *menuRectPtr );
void  DoChooseMessage( MenuHandle menu, Rect *menuRectPtr,
  Point hitPt, short *whichItemPtr );
void  InvertItem( short itemNumber, short itemHeight, 
  Rect *menuRectPtr );
void  DrawCenteredPict( PicHandle pic, Rect *rectPtr );
void  CalcitemHeightAndWidth( short basePICTid, short numPICTs,
 short *widthPtr, short *heightPtr );
void  GetNumPICTs( MenuHandle menu, short *baseIDPtr,
 short *numPICTsPtr );


/* 2 */
pascal void main( short message,
 MenuHandle menu,
 Rect *menuRectPtr,
 Point hitPt,
 short *whichItemPtr )
 switch( message )
 case mDrawMsg:
 DoDrawMessage( menu, menuRectPtr );
 case mChooseMsg:
 DoChooseMessage( menu,menuRectPtr,hitPt,whichItemPtr );
 case mSizeMsg:
 DoSizeMessage( menu, menuRectPtr );


/* 3 */
void  DoSizeMessage( MenuHandle menu,
 Rect *menuRectPtr )
 short  basePICTid, numPICTs, maxPICTWidth, maxPICTHeight;
 GetNumPICTs( menu, &basePICTid, &numPICTs );
 CalcitemHeightAndWidth( basePICTid, numPICTs, &maxPICTWidth,
   &maxPICTHeight );
 (**menu).menuWidth = maxPICTWidth + 2 * kLeftMargin;
 (**menu).menuHeight = (maxPICTHeight + kTopMargin*2) * numPICTs;


/* 4 */
void  DoDrawMessage( MenuHandle menu,
 Rect *menuRectPtr )
 short  basePICTid, numPICTs, maxPICTWidth, 
 maxPICTHeight, itemHeight, i;
 Rect   r, tempRect;
 GetNumPICTs( menu, &basePICTid, &numPICTs );
 CalcitemHeightAndWidth(  basePICTid, numPICTs, 
 &maxPICTWidth, &maxPICTHeight );
 itemHeight = maxPICTHeight + kTopMargin * 2; = menuRectPtr->top + kTopMargin;
 r.left = menuRectPtr->left + kLeftMargin;
 r.bottom = + maxPICTHeight;
 r.right = r.left + maxPICTWidth;
 for ( i=0; i<numPICTs; i++ )
 pic = GetPicture( basePICTid + i );
 DrawCenteredPict( pic, &r );
 OffsetRect( &r, 0, itemHeight );


/* 5 */
void  DoChooseMessage(  MenuHandle menu,
 Rect *menuRectPtr,
 Point hitPt,
 short *whichItemPtr )
 short  basePICTid, selectedItem, numPICTs, 
 maxPICTWidth, maxPICTHeight, itemHeight;
 Rect   r;
 GetNumPICTs( menu, &basePICTid, &numPICTs );
 CalcitemHeightAndWidth(  basePICTid, numPICTs, 
 &maxPICTWidth, &maxPICTHeight );
 itemHeight = (2 * kTopMargin) + maxPICTHeight;
 if ( PtInRect( hitPt, menuRectPtr ) )
 selectedItem = ( (hitPt.v - menuRectPtr->top) / 
 itemHeight ) + 1;
 if ((*whichItemPtr > 0) && (*whichItemPtr != selectedItem))
 InvertItem( *whichItemPtr, itemHeight, menuRectPtr );
 if ( *whichItemPtr != selectedItem )
 *whichItemPtr = selectedItem;
 InvertItem( *whichItemPtr, itemHeight, menuRectPtr );
 else if ( *whichItemPtr > 0 )
 InvertItem( *whichItemPtr, itemHeight, menuRectPtr );
 *whichItemPtr = 0;


/* 6 */
void  InvertItem( short itemNumber,
 short itemHeight,
 Rect *menuRectPtr )
 Rect r;
 r = *menuRectPtr; += ( (itemNumber-1) * itemHeight );
 r.bottom = + itemHeight;
 InvertRect( &r );


/* 7 */
void  DrawCenteredPict( PicHandle pic,
 Rect *rectPtr )
 Rect pictRect;
 pictRect = (**pic).picFrame;
 OffsetRect( &pictRect, rectPtr->left - pictRect.left,
    rectPtr->top  -;
 OffsetRect( &pictRect,(rectPtr->right - pictRect.right)/2,
   (rectPtr->bottom - pictRect.bottom)/2);
 DrawPicture( pic, &pictRect );


/* 8 */
void  CalcitemHeightAndWidth( short basePICTid,
 short numPICTs,
 short *widthPtr,
 short *heightPtr )
 short  i;
 Rect   r;
 *widthPtr = 0;
 *heightPtr = 0;
 for ( i=0; i<numPICTs; i++ )
 pic = GetPicture( basePICTid + i );
 r = (**pic).picFrame;
 if ( r.bottom - > *heightPtr )
 *heightPtr = r.bottom -;
 if ( r.right - r.left > *widthPtr )
 *widthPtr = r.right - r.left;


/* 9 */
void  GetNumPICTs( MenuHandle menu,
 short *baseIDPtr,
 short *numPICTsPtr )
 Handle longHandle;
 long retrievedLong;
 short  menuID;
 menuID = (**menu).menuID;
 longHandle = GetResource( 'long', menuID );
 retrievedLong = (*((long *)(*longHandle)));
 *baseIDPtr = HiWord( retrievedLong );
 *numPICTsPtr = LoWord( retrievedLong );

Save your source code. Next, select Set Project Type... from the Project menu. When the dialog appears, click on the Code Resource radio button. Now make your dialog box look like the one in Figure 1. Be sure to check every single field!

Figure 1. The Set Project Type... dialog box.

The File Type and Creator fields will make your MDEF file look like a ResEdit document. That way, when you double-click on the file MDEF.rsrc (which we’re about to create) you’ll automatically launch ResEdit.

Why do this? Well, if we create the MDEF resource in a file, we’ll eventually want to copy the MDEF into the resource file (or application) that will use the MDEF. We’ll most likely do this in ResEdit.

Now select Build Code Resource... from the Project menu. You’ll be prompted to name the file the MDEF resource will be copied to. There are two approaches you can use. If you plan on using this resource in more than one application, you should save it as its own resource file. That’s what we’ll do. Enter the name MDEF.Π.rsrc and press the Save button.

The second approach we could have taken would be to click on the Merge checkbox, then entering the name of the resource file of the application that will be using the MDEF. If you do this, the MDEF resource will be copied into the application’s resource file, which is really what you want. We’ll do the same thing by hand.

Creating the Tester Resources

Now that your MDEF is complete, you’ll build an application to test the sucker. We’ll start by building the project resources. Start ResEdit and create a new file in the MDEF Files folder called Tester.Π.rsrc. Now open the file MDEF.Π.rsrc, click on the MDEF icon, and select Copy from the Edit menu. Now click on the Tester.Π.rsrc window and select Paste from the Edit menu. The MDEF icon should appear in the Tester.Π.rsrc window. When you double-click on the MDEF icon, you should see a single MDEF with an ID of 128. So far, so good.

Next, create a WIND resource with an ID of 128, a top of 40, Left of 2, Height of 160, and Width of 200. Click on the second icon from the left for the window type. Make the window not visible.

Next, create an MBAR resource (with ID 128) with four menus in it, numbered 128, 129, 130, and 131.

Next, create four MENU resources using the pictures in Figure 2 as a guide. Note that MENU 131 has a title (Pictures) but no items.

Figure 2. The four MENU resources.

Now comes a critical step. Open up the MENU editor to edit MENU 131. Select Edit Menu & MDEF ID... from the MENU menu. A dialog box will appear allowing you to set the MENU and MDEF resource IDs for this MENU. Change the MDEF ID from 0 to 128. Leave the MENU ID as is.

Be sure you change the MDEF id. If you don’t, the program will not work!

Next, you’ll create a custom resource that will tell the MDEF the resource ID of the first PICT to display, as well as the number of PICTs to display in the menu. Close all the windows till you are back in the main Tester.Π.rsrc window. Now select Create New Resource from the Resource menu. When prompted for a resource type, enter the four characters long. Since ResEdit doesn’t have a ‘long’ template, it will throw you into the hex/ASCII editor. Use the hex side and enter the hex number 00800005. For a peek at mine, check out Figure 3.

Figure 3. The long resource.

Next, select Get Resource Info from the Resource menu to change the resource ID to 131. You must make this change, so the MDEF will associate this resource with MENU 131.

The first two bytes of the long resource tell the MDEF to start off with PICT 128 (in hex, that’s 0080) and to use 5 PICT resources in a row (128, 129, 130, 131, and 132). Oh, by the way, I called this resource long because it is always 4 bytes in length.

Once you’ve changed the long resource ID to 131 (you did do that, didn’t you?) you are ready to create the PICT resources. Create five of them, being sure that they are numbered from 128 to 132. Color is fine. For best results, you might want to keep all of them around the size of an icon. My five are shown in Figure 4.

Figure 4. My five PICTs.

Save your resource file and quit ResEdit.

Creating the Tester Project

In THINK C, create a new project in the MDEF Files folder called Tester.Π. Add MacTraps to the project. Create a new source code file named Tester.c and add it to the project. Here’s the source code:

/* 10 */
#define kWindowResID 128
#define kMBARResID 128
#define kNULLStorage 0L
#define kMoveToFront (WindowPtr)-1L
#define kSleep   60L

#define mApple   128
#define iAbout   1

#define mFile    129
#define iQuit    1

#define mPICT    131

/*  Globals  */

Boolean gDone;
short   gCurPICTid;

/*  Functions  */

void  ToolboxInit( void );
void  MenuBarInit( void );
void  WindowInit( void );
void  EventLoop( void );
void  DoEvent( EventRecord *eventPtr );
void  HandleMouseDown( EventRecord *eventPtr );
void  HandleMenuChoice( long menuChoice );
void  HandleAppleChoice( short item );
void  HandleFileChoice( short item );
void  HandlePICTChoice( short item );
void  DoUpdate( WindowPtr window );
void  DrawPictInWindow( PicHandle pic, WindowPtr window );
short GetBasePICTid( short menuID );


/* 11 */
void  main( void )
 gCurPICTid = GetBasePICTid( mPICT );


/* 12 */
void  ToolboxInit( void )
 InitGraf( &thePort );
 InitDialogs( NULL );


/* 13 */
void  MenuBarInit( void )
 Handle menuBar;
 MenuHandle menu;
 menuBar = GetNewMBar( kMBARResID );
 SetMenuBar( menuBar );

 menu = GetMHandle( mApple );
 AddResMenu( menu, 'DRVR' );


/* 14 */
void  WindowInit( void )
 window = GetNewWindow( kWindowResID,kNULLStorage,kMoveToFront);
 if ( window == NULL )
 SysBeep( 20 );  /* Couldn't load WIND */
 SetPort( window );
 ShowWindow( window );


/* 15 */
void  EventLoop( void )
 gDone = false;
 while ( gDone == false )
 if ( WaitNextEvent( everyEvent, &event, kSleep, nil ) )
 DoEvent( &event );


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


/* 17 */
void  HandleMouseDown( EventRecord *eventPtr )
 short  thePart;
 long   menuChoice;
 thePart = FindWindow( eventPtr->where, &window );
 switch ( thePart )
 case inMenuBar:
 menuChoice = MenuSelect( eventPtr->where );
 HandleMenuChoice( menuChoice );
 case inSysWindow: 
 SystemClick( eventPtr, window );
 case inDrag : 
 DragWindow( window, eventPtr->where, &(screenBits.bounds) );


/* 18 */
void  HandleMenuChoice( long menuChoice )
 short  menu;
 short  item;
 if ( menuChoice != 0 )
 menu = HiWord( menuChoice );
 item = LoWord( menuChoice );
 switch ( menu )
 case mApple:
 HandleAppleChoice( item );
 case mFile:
 HandleFileChoice( item );
 case mPICT:
 HandlePICTChoice( item );
 HiliteMenu( 0 );


/* 19 */
void  HandleAppleChoice( short item )
 MenuHandle appleMenu;
 Str255 accName;
 short  accNumber;
 switch ( item )
 case iAbout:
 SysBeep( 20 );
 appleMenu = GetMHandle( mApple );
 GetItem( appleMenu, item, accName );
 accNumber = OpenDeskAcc( accName );


/* 20 */
void  HandleFileChoice( short item )
 switch ( item )
 case iQuit :
 gDone = true;


/* 21 */
void  HandlePICTChoice( short item )
 window = FrontWindow();
 EraseRect( &window->portRect );
 InvalRect( &window->portRect );
 gCurPICTid = GetBasePICTid( mPICT ) + item - 1;


/* 22 */
void  DoUpdate( WindowPtr window )
 BeginUpdate( window );
 pic = GetPicture( gCurPICTid );

 if ( pic == NULL )
 SysBeep( 20 );  /* Couldn't load PICT */
 DrawPictInWindow( pic, FrontWindow() );
 EndUpdate( window );


/* 23 */
void  DrawPictInWindow( PicHandle pic,
 WindowPtr window )
 Rect   pictRect, windRect;
 pictRect = (**pic).picFrame;
 windRect = window->portRect;
 OffsetRect(&pictRect, windRect.left - pictRect.left, -;
 OffsetRect(&pictRect,(windRect.right - pictRect.right)/2,
 (windRect.bottom - pictRect.bottom)/2);
 DrawPicture( pic, &pictRect );


/* 24 */
short GetBasePICTid( short menuID )
 Handle longHandle;
 long retrievedLong;
 longHandle = GetResource( 'long', menuID );
 retrievedLong = (*((long *)(*longHandle)));
 return( HiWord( retrievedLong ) );

Once the code is typed in, save your changes and run this puppy.

Running the MDEF Tester

When you run your application, the first thing you should see is a window with PICT 128 centered in it. Now, for the big moment. Drumroll, please! Click your mouse on the Pictures menu. A menu should appear with your five PICTs in it. Select a picture. The selected picture should appear in the window. Figure 5 shows my menu, with Clarus the Dog-Cow selected. Moof!

Figure 5. My Pictures menu, with the second picture selected.

Till Next Month

Next month, we’ll walk through the code and talk about code resources in general. Till then, Daniel and I will be busy putting together his new swing set. Later...


Community Search:
MacTech Search:

Software Updates via MacUpdate

World of Tanks Generals guide - Tips and...
World of Tanks Generals is a brand new card game by the developer behind the World of Tanks shooter franchise. It plays like a cross between chess and your typical card game. You have to keep in consideration where you place your tanks on the board... | Read more »
TruckSimulation 16 guide: How to succeed...
Remember those strangely enjoyable truck missions in Grand Theft Auto V whereit was a disturbing amount of fun to deliver cargo? TruckSimulation 16 is reminiscent of that, and has you play the role of a truck driver who has to deliver various... | Read more »
The best GIF making apps
Animated GIFs have exploded in popularity recently which is likely thanks to a combination of Tumblr, our shorter attention spans, and the simple fact they’re a lot of fun. [Read more] | Read more »
The best remote desktop apps for iOS
We've been sifting through the App Store to find the best ways to do computer tasks on a tablet. That gave us a thought - what if we could just do computer tasks from our tablets? Here's a list of the best remote desktop apps to help you use your... | Read more »
Warhammer 40,000: Freeblade guide - How...
Warhammer 40,000: Freebladejust launched in the App Store and it lets you live your childhood dream of blowing up and slashing a bunch of enemies as a massive, hulking Space Marine. It's not easy being a Space Marine though - and particularly if... | Read more »
Gopogo guide - How to bounce like the be...
Nitrome just launched a new game and, as to be expected, it's a lot of addictive fun. It's called Gopogo, and it challenges you to hoparound a bunch of platforms, avoiding enemies and picking up shiny stuff. It's not easy though - just like the... | Read more »
Sago Mini Superhero (Education)
Sago Mini Superhero 1.0 Device: iOS Universal Category: Education Price: $2.99, Version: 1.0 (iTunes) Description: KAPOW! Jack the rabbit bursts into the sky as the Sago Mini Superhero! Fly with Jack as he lifts impossible weights,... | Read more »
Star Wars: Galaxy of Heroes guide - How...
Star Wars: Galaxy of Heroes is all about collecting heroes, powering them up, and using them together to defeat your foes. It's pretty straightforward stuff for the most part, but increasing your characters' stats can be a bit confusing because it... | Read more »
The best cooking apps (just in time for...
It’s that time of year again, where you’ll be gathering around the dinner table with your family and a huge feast in front of you. [Read more] | Read more »
Square Rave guide - How to grab those te...
Square Rave is an awesome little music-oriented puzzle game that smacks of games like Lumines, but with its own unique sense of gameplay. To help wrap your head around the game, keep the following tips and tricks in mind. [Read more] | Read more »

Price Scanner via

13-inch 128GB MacBook Air now on sale for $79...
Best Buy has just lowered their price on the 2015 13″ 1.6GHz/128GB MacBook Air to $799.99 on their online store for Cyber Monday. Choose free shipping or free local store pickup (if available). Sale... Read more
Best Buy lowers 13-inch MacBook Pro prices, n...
Best Buy has lowered prices on select 13″ MacBook Pros this afternoon. Now save up to $200 off MSRP for Cyber Monday on the following models. Choose free shipping or free local store pickup (if... Read more
Cyber Monday: Apple MacBooks on sale for up t...
Apple resellers have MacBook Pros, MacBook Airs, and MacBooks on sale for up to $250 off MSRP for Cyber Monday 2015. The following is a roundup of the lowest prices available for new models from any... Read more
Cyber Monday: Apple Watch on sale for up to $...
B&H Photo has the Apple Watch on sale for Cyber Monday for $50-$100 off MSRP. Shipping is free, and B&H charges NY sales tax only: - Apple Watch Sport: $50 off - Apple Watch: $50-$100 off B... Read more
Cyber Monday: 15% off Apple products, and sto...
Use code CYBER15 on Cyber Monday only to take 15% on Apple products at Target, and store-wide. Choose free shipping or free local store pickup (if available). Sale prices for online orders only, in-... Read more
iPad Air 2 And iPad mini Among Top Five Black...
Adobe has released its 2015 online shopping data for Black Friday and Thanksgiving Day. The five best selling electronic products on Black Friday were Samsung 4K TVs, Apple iPad Air 2, Microsoft Xbox... Read more
All-in-one PC Shipments Projected To Drop Ove...
Digitimes’ Aaron Lee and Joseph Tsai report that all-in-one (AIO) PC shipments may drop a double-digit percentage on-year in 2015 due to weaker-than-expected demand, although second-largest AIO make... Read more
Sprint Offers iPad Pro
Sprint now offers Apple’s new iPad Pro with Wi-Fi + Cellular, featuring a 12.9-inch Retina display with 5.6 million pixels. Customers can pick up iPad Pro at select Sprint retail locations. It can... Read more
Cyber Monday: Target offers 15% discount on A...
Target has discounted Apple Watches by 15% for Cyber Monday. Choose free shipping or free local store pickup (if available). Sale prices for online orders only, in-store prices may vary: - Apple... Read more
Sunday roundup of Holiday weekend Mac sales:...
Take up to $500 off MSRP on the price of a new Mac at B&H Photo today as part of their Black Friday/Holiday weekend sale. Shipping is free, and B&H charges NY tax only. These prices are... Read more

Jobs Board

*Apple* Site Security Manager - Apple (Unite...
# Apple Site Security Manager Job Number: 42975010 Culver City, Califo ia, United States Posted: Oct. 2, 2015 Weekly Hours: 40.00 **Job Summary** The Apple Site Read more
iOS Wallet & *Apple* Pay Engineer - App...
# iOS Wallet & Apple Pay Engineer Job Number: 40586801 Santa Clara Valley, Califo ia, United States Posted: Nov. 16, 2015 Weekly Hours: 40.00 **Job Summary** The iOS Read more
*Apple* Online Store Expansion - Apple (Unit...
# Apple Online Store Expansion Job Number: 41191932 Santa…1, 2015 Weekly Hours: 40.00 **Job Summary** The Online Apple Store is seeking a person to lead its Read more
Software Engineer, *Apple* Watch - Apple (U...
# Software Engineer, Apple Watch Job Number: 38181776 Santa Clara Valley, Califo ia, United States Posted: Nov. 2, 2015 Weekly Hours: 40.00 **Job Summary** The Apple Read more
Technical Program Manager, Strategic Merchant...
# Technical Program Manager, Strategic Merchants - Apple Pay Job Number: 44001177 Santa Clara Valley, Califo ia, United States Posted: Oct. 30, 2015 Weekly Hours: 40.00 Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.