TweetFollow Us on Twitter

Sprocket Menus 1
Volume Number:11
Issue Number:5
Column Tag:Getting Started

Sprocket Menus, Part 1

By Dave Mark, MacTech Magazine Regular Contributing Author

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

My February ’93 Getting Started column featured a program called MenuMaster. MenuMaster constructed a menu bar consisting of four menus: The traditional Apple, File, and Edit menus, as well as a special Options menu (Figure 1). Selecting the first item changes it from Change My Name to Change Me Back Again. Selecting the first item again changes it back to Change My Name.

Selecting Disable Me disables the second item and enables the third item. If you then select the newly enabled Enable Previous Item, it gets disabled and Disable Me is reenabled.

If you select Add Extra Menu, a new menu is inserted in the menu bar and Add Extra Menu is disabled. The new menu, titled Extra Menu, features a single item, Delete Me. Selecting Delete Me deletes the extra menu from the menu bar and reenables Add Extra Menu.

Finally, selecting Append Item adds an extra item (Can’t Delete Me...) to the end of the menu. As its names implies, there’s no way to delete this extra item.

Fig. 1. MenuMaster’s Options menu.

A Sprocket Version of MenuMaster

This month we’re going to use Sprocket to implement most of MenuMaster’s functionality. We’ll skip the ability to append an item to the end of a menu for two reasons. First, appending a single item to the end of a menu just isn’t done that often and isn’t particularly useful. More importantly (and probably for the same reason), Sprocket doesn’t give you an easy way to append a new item to a menu.

If you come up with a good reason to add this functionality to Sprocket (or if you have any comments or bugs to report), send e-mail to

As I mentioned last month, Sprocket based its menu-handling model on that used by OpenDoc. At the heart of this model is a replacement for the MENU resource type. A CMNU resource is just like a MENU resource, with one important addition. Each menu item features a command number. You’ll use this command number to refer to the item, instead of the more traditional method of specifying the menu the item belongs to, along with the item’s position in the menu (e.g., menu 129, item 4).

Figure 2. The CMNU resource, featuring a Cmd-Num field for each menu item.

Check out the ResEdit snapshot in Figure 2. It shows the CMNU resource that represents our new Options menu. The first menu item, Change My Name, is selected. The command number for this item is 1000. When the user selects this item, Sprocket will pass the associated command number (in this case, 1000) as a parameter to the routine HandleMenuCommand() (it’s in the file SprocketStarter.cp). Instead of creating a separate item dispatch routine for each menu (HandleAppleMenu(), HandleFileMenu(), etc.), you’ll create a single switch statement containing cases for all your commands.

Sprocket automatically creates a menu bar at application startup. In C++ terms, Sprocket constructs a TMenuBar object, which is implemented in the files TMenuBar.cp and TMenuBar.h. Here’s the TMenuBar class definition:

class TMenuBar
Resource ('MBAR' and 'CMNU') Utilities
 OSErr  GetNewMenuBar(short whichMBAR);
 MenuRefGetMenuFromCMNU(short whichMenu);
Menu command mapping functions

 MenuCommandID   GetCommand(MenuID menu, MenuItemID item);
 void   GetMenuAndItem(MenuCommandID commandNum, 
 MenuID * returnedMenu, MenuItemID * returnedItem);
 OSErr  RegisterCommand(  MenuCommandID commandNum, 
   MenuID menu, MenuItemID item);
 OSErr  UnregisterCommand(MenuCommandID commandNum);
Menu enable/disable routines for menu items

 void   EnableCommand(MenuCommandID commandNum, 
 Boolean enable);
 void   EnableAndCheckCommand(MenuCommandID commandNum, 
 Boolean enable, Boolean check);
 void   GetItemString(MenuCommandID commandNum,
 StringPtr itemString);
 void   SetItemString(MenuCommandID commandNum,
 StringPtr itemString);
helpful utility functions
 void   HideMenuBar();
 void   ShowMenuBar();
 void   RedrawIfNeeded();
 void   Invalidate();
 void   Validate();

 static Boolean  fgMenuBarNeedsRedraw;
 static Boolean  fgMenuBarHidden;
mapping tables
 TMenuCommandTable fCommandTable;
 TMenuItemTable  fMenuItemTable;
internal methods
 MenuHandle GetMenuHandleAndItemFromCommand(
 MenuCommandID commandNum, 
 MenuID *menu,MenuItemID *item);

The first member function, GetNewMenuBar() uses the specified MBAR resource to build a new menu bar. Though this version of Sprocket only creates a single menu bar, this might not be the case in the future. For now, a pointer to the menu bar object is stored in the global gMenuBar. Take a minute to open up the file SprocketMain.cp and check out the code around line 363. This is where Sprocket creates the TMenuBar object based on the MBAR resource in SprocketStarter.rsrc.

The member function GetMenuFromCMNU() loads a CMNU resource and walks through it, one item at a time. It builds a traditional menu structure, passing each item’s command number to the RegisterCommand() member function, which adds the command to Sprocket’s menu command table. If you are going to take advantage of Sprocket’s menu command mechanism, you must register your menu item commands. If you base your menus on a CMNU resource, GetMenuFromCMNU() will register your menu items automatically. If the menus in your MBAR resource correspond to a CMNU resource, Sprocket will register the menu items automatically.

If you don’t want to use a CMNU resource, you can still add and delete your menus to and from the global menu bar yourself. For example, since a font or size menu will have a dynamic number of items, the CMNU resource just doesn’t make sense. We’ll look at that process in a future column.

The member function GetCommand() takes a menu and item ID and returns the associated command. GetMenuAndItem() takes a command and returns the associated menu and item ID.

If you want to delete a menu whose commands have been registered, you can use the UnregisterCommand() member function to, one-at-a-time, unregister the commands in that menu. Otherwise, you’ll orphan commands in the command table.

EnableCommand() and EnableAndCheckCommand() let you enable, disable, check, and uncheck a menu command. GetItemString() and SetItemString() allow you to retrieve and set an items name using its command.

HideMenuBar() and ShowMenuBar() let you hide and show the menu bar (what a concept!). Invalidate() marks the menu bar as needing to be redrawn. Validate() sets the menu bar as up to date. RedrawIfNeeded() redraws the menu bar if the invalid flag has been set. Note that RedrawIfNeeded() is called in Sprocket’s main event loop, so there’s no need for you to call it yourself.

This Month’s Resources

Sprocket gets its resources from four different resource files. CreditsBox.rsrc contains the resources used to build the Sprocket about box. StandardMenus.rsrc contains some standard MENU and CMNU resources. If you want to change any of these menus, copy the appropriate resource from StandardMenus.rsrc into SprocketStarter.rsrc and delete the original from StandardMenus.rsrc. Modify the version you copied into SprocketStarter.rsrc.

Sprocket.rsrc contains various resources used by Sprocket and should not be modified. SprocketStarter.rsrc is your resource center. Put all the resources you add to Sprocket there.

You’ll need to modify one resource and add three new ones to SprocketStarter.rsrc. First, open up MBAR 128 and add menu ID 1000 to the list already in place.

If you’re not using Projector (the sourced code control system), you might want to delete the ckid resources you’ll find in each of the resource files. That will get rid of the annoying link error complaining about the multiply-defined resource.

Next, you’ll create your three CMNU resources. The first represents the Options menu we want to add to the end of the menu bar. In general, when you add a new resource to Sprocket, you’ll start numbering your resources from 1000, instead of at 128 the way you normally would. This is just a convention, and might change as Sprocket grows up.

When you create CMNU 1000, be sure to change the resource ID in both places: once in the “Get Info” box and also in the “Edit Menu and MDEF ID” dialog.

Figure 3. CMNU 1000

Enter a command number of 1000 for the item Change My Name, 1001 for Disable Me, 1002 for Enable Previous Item, 1003 for Add Extra Menu, and 1004 for Beeps. Next, disable the item Enable Previous Item. After that, click on the Beeps item, check the has SubMenu checkbox and enter 100 as the submenu ID (Figure 4). Since submenu IDs are limited to a single byte, we won’t be able to give the submenu CMNU resource an ID greater than 1000. So much for sticking to conventions!

Figure 4. The Beeps item, with its submenu ID of 100 entered.

Next, create a new CMNU resource with an ID of 1001 (Once again, be sure to change the ID in both places). The menu will have a title of Extra Menu and a single item, Delete This Menu. Give the item Delete This Menu a command of 1007 (Figure 5).

Figure 5. CMNU 1001

Finally, create a CMNU resource with an ID of 100. Add two items, Beep Once with a command ID of 1005 and Beep Twice with a command ID of 1006 (Figure 6).

Figure 6. CMNU 100.

Save your changes and quit your resource editor.

Modifying the Source Code

Now launch CodeWarrior or Symantec C++ and edit SprocketStarter.h. Start by adding this global reference to the file:

extern Boolean   gItemNameChanged;

gItemNameChanged is a Boolean that indicates whether the item Change My Name has been selected. It tells us whether the item should read Change My Name or Change Me Back Again.

Next, add this enum to the file:

 mSubMenu = 100,
 mExtraMenu = 1001,
 cChangeName= 1000,
 cDisableMe = 1001,
 cEnablePrevious = 1002,
 cAddExtraMenu   = 1003,
 cBeeps = 1004,
 cBeepOnce= 1005,
 cBeepTwice = 1006,
 cDeleteExtraMenu= 1007

The first two constants specify the two CMNU resource IDs. The next 8 specify the menu command IDs. Notice that the menu constants start with a lower case “m” and the commands start with a lower case “c”. Unfortunately, the Apple event registry starts all its class names with a lower-case “c”, so be on the lookout for name collisions.

Next, add these three constants to the file:

const StringPtr kUnchangedName = "\pChange My Name";
const StringPtr kChangedName = "\pChange Me Back Again";
const short kLastMenu = 0;

The first two are just Pascal strings we used for the menu names. We really should have implemented these strings as ‘STR ’ resources to make the code easier to localize. In general, I try never to specify strings in code, but I guess I was just feeling a bit lazy.

The last constant will be used in our call of InsertMenu(), telling InsertMenu() to insert the menu at the end of the menu bar.

Next, edit the file SprocketStarter.cp. Start by adding this global definition at the top of the file:

Boolean gItemNameChanged = false;

Next, add these three lines to the beginning of the routine SetUpApplication():

MenuRef hierMenu;

hierMenu = gMenuBar->GetMenuFromCMNU( mSubMenu );
InsertMenu( hierMenu, -1 ); 

GetMenuFromCMNU() loads CMNU 100, registers all the commands, and returns a MenuHandle to a standard menu based on the CMNU resource. InsertMenu() inserts the resulting menu in the menu bar.

Finally, add the cases to handle our new commands to the switch in HandleMenuCommand() further down in SprocketStarter.cp. Here’s my edited copy of HandleMenuCommand():

HandleMenuCommand(MenuCommandID theCommand)
 OSErr  err;
 switch (theCommand)
 case cAbout:
 case cNew:
 case cOpen:
 case cPreferences:
 TPreferencesDialogWindow * prefsDialog = 
 new TPreferencesDialogWindow;
 case cNewMailableWindow:
 TMailableDocWindow *aWackyThing = new TMailableDocWindow;

Here come the new commands. This first one switches the first menu item between Change My Name and Change Me Back Again. Notice that we’re using the global TMenuBar object to change the menus. If Sprocket ever gets modified to use more than one menu bar, we’ll have to modify this code to be sure we use the menu bar that contains the menu we want to work with. Of course, if that happens, you can count on some sample code in this column to show you how to do that.

 case cChangeName:
 if ( gItemNameChanged )
 gMenuBar->SetItemString( cChangeName, kUnchangedName );
 gMenuBar->SetItemString( cChangeName, kChangedName );
 gItemNameChanged = ! gItemNameChanged;

This command disables Disable Me and enables Enable Previous Item.

 case cDisableMe:
 gMenuBar->EnableCommand( cDisableMe, false );
 gMenuBar->EnableCommand( cEnablePrevious, true );

This command does just the opposite.

 case cEnablePrevious:
 gMenuBar->EnableCommand( cDisableMe, true );
 gMenuBar->EnableCommand( cEnablePrevious, false );

This command disables the item that spawned this command in the first place (Add Extra Menu), then builds a new menu from the extra menu CMNU resource. We add the new menu to the end of the menu bar, then call Invalidate() to force the menu bar to get redrawn.

 case cAddExtraMenu:
 gMenuBar->EnableCommand( cAddExtraMenu, false );
 extraMenu = gMenuBar->GetMenuFromCMNU( mExtraMenu );
 InsertMenu( extraMenu, kLastMenu );


This command deletes the extra menu we added with the previous command. First, we reenable the Add Extra Menu item. Notice that we didn’t have to retrieve the menu that this item belongs to. All we needed was the command. This definitely makes life a lot simpler.

 case cDeleteExtraMenu:
 gMenuBar->EnableCommand( cAddExtraMenu, true );

Since the TMenuBar class doesn’t support a DeleteCMNU() method, we’ll have to deregister the command by hand. A DeleteCMNU() method would step through all the items in the specified menu, calling UnregisterCommand() for each item. It would then delete the menu for us. Since our extra menu only contains a single item, it’s no big deal to do this by hand. Once we are done, we’ll force a menu bar redraw. Look for a DeleteCMNU() method in a future version of Sprocket.

 err = gMenuBar->UnregisterCommand( cDeleteExtraMenu );
 DeleteMenu( mExtraMenu );

This next command corresponds to the parent menu of our hierarchical submenu. Normally, this command will never get called because the menu manager won’t detect a selection of the parent item of a submenu (Figure 7). There are times when this is useful, however. For example, imagine if you built a menu of applications, where each application item had a submenu listing some frequently used documents that can be opened by that application (NowMenus does this). If you select a document from a submenu, its parent application gets launched and opens the selected document. If you release the mouse with the application selected (without selecting a document from the submenu), you might want to launch the application without specifying a document.

The point here is this: Specify commands for all your menu items, even the hierarchical parent menus. A future version of Sprocket might include a workaround to execute commands associated with these currently orphaned items.

 case cBeeps:

Figure 7. A menu item with its submenu showing.
If the mouse button was released at this point, the Beeps item
(rather than either of the submenu items) would be selected.

These next two items are horribly technical. They beep either once or twice, depending on the item selected.

 case cBeepOnce:
 SysBeep( 20 );
 case cBeepTwice:
 SysBeep( 20 ); SysBeep( 20 );

Till Next Month

There are still some concepts that we need to get into regarding Sprocket and menus. For example, when do you make the decision about which menu items you will enable and disable to ensure that things are set up correctly before a user makes a selection from a menu. How should the frontmost window affect which menu items are enabled or disabled? We’ll explore these important issues in next month’s column. See you then!


Community Search:
MacTech Search:

Software Updates via MacUpdate

Apple Safari 10.0.1 - Apple's Web b...
Note: The direct download link is currently unavailable. It is available in the OS X 10.11.6 release, as well as in the Apple Security Updates. Apple Safari is Apple's web browser that comes with OS... Read more
Apple macOS Sierra 10.12.1 - The latest...
With Apple macOS Sierra, Siri makes its debut on Mac, with new features designed just for the desktop. Your Mac works with iCloud and your Apple devices in smart new ways, and intelligent... Read more
Apple iOS 10.1 - The latest version of A...
iOS 10 is the biggest release of iOS ever. A massive update to Messages brings the power of the App Store to your conversations and makes messaging more personal than ever. Find your route with... Read more
Hazel 4.0.7 - Create rules for organizin...
Hazel is your personal housekeeper, organizing and cleaning folders based on rules you define. Hazel can also manage your trash and uninstall your applications. Organize your files using a familiar... Read more
Opera 40.0.2308.90 - High-performance We...
Opera is a fast and secure browser trusted by millions of users. With the intuitive interface, Speed Dial and visual bookmarks for organizing favorite sites, news feature with fresh, relevant content... Read more
BetterTouchTool 1.93 - Customize Multi-T...
BetterTouchTool adds many new, fully customizable gestures to the Magic Mouse, Multi-Touch MacBook trackpad, and Magic Trackpad. These gestures are customizable: Magic Mouse: Pinch in / out (zoom... Read more
Backblaze - Online backup serv...
Backblaze is an online backup service designed from the ground-up for the Mac. With unlimited storage available for $5 per month, as well as a free 15-day trial, peace of mind is within reach with... Read more
Postbox 5.0.5 - Powerful and flexible em...
Postbox is a new email application that helps you organize your work life and get stuff done. It has all the elegance and simplicity of Apple Mail, but with more power and flexibility to manage even... Read more
Coda 2.5.19 - One-window Web development...
Coda is a powerful Web editor that puts everything in one place. An editor. Terminal. CSS. Files. With Coda 2, we went beyond expectations. With loads of new, much-requested features, a few surprises... Read more
Toast Titanium 15.1 - $99.99
Roxio Toast 15 Titanium, the leading DVD burner for Mac, makes burning even better, adding Roxio Secure Burn to protect your files on disc and USB in Mac- or Windows-compatible formats. Get more... Read more

Latest Forum Discussions

See All

WitchSpring2 (Games)
WitchSpring2 1.27 Device: iOS Universal Category: Games Price: $3.99, Version: 1.27 (iTunes) Description: This is the story of Luna, the Moonlight Witch as she sets out into the world. This is a sequel to Witch Spring. Witch Spring 2... | Read more »
4 popular apps getting a Halloween makeo...
'Tis the season for all things spooky. So much, so, in fact, that even apps are getting into the spirt of things, dressing up in costume and spreading jack o' lanterns all about the place. These updates bring frightening new character skins, scary... | Read more »
Pokémon GO celebrates Halloween with can...
The folks behind Pokémon GO have some exciting things planned for their Halloween celebration, the first in-game event since it launched back in July. Starting October 26 and ending on November 1, trainers will be running into large numbers of... | Read more »
Best Fiends Forever Guide: How to collec...
The fiendship in Seriously's hit Best Fiends has been upgraded this time around in Best Fiends Forever. It’s a fast-paced clicker with lots of color and style--kind of reminiscent of a ‘90s animal mascot game like Crash Bandicoot. The game... | Read more »
5 apps for the budding mixologist
Creating your own cocktails is something of an art form, requiring a knack for unique tastes and devising interesting combinations. It's easy to get started right in your own kitchen, though, even if you're a complete beginner. Try using one of... | Read more »
5 mobile strategy games to try when you...
Strategy enthusiasts everywhere are celebrating the release of Civilization VI this week, and so far everyone seems pretty satisfied with the first full release in the series since 2010. The series has always been about ultra-addictive gameplay... | Read more »
Popclaire talk to us about why The Virus...
Humanity has succumbed to a virus that’s spread throughout the world. Now the dead have risen with a hunger for human flesh, and all that remain are a few survivors. One of those survivors has just called you for help. That’s the plot in POPCLAIRE’... | Read more »
Oceans & Empires preview build sets...
Hugely ambitious sea battler Oceans & Empires is available to play in preview form now on Google Play - but download it quickly, as it’s setting sail away in just a few days. [Read more] | Read more »
Rusty Lake: Roots (Games)
Rusty Lake: Roots 1.1.4 Device: iOS Universal Category: Games Price: $2.99, Version: 1.1.4 (iTunes) Description: James Vanderboom's life drastically changes when he plants a special seed in the garden of the house he has inherited.... | Read more »
Flippy Bottle Extreme! and 3 other physi...
Flippy Bottle Extreme! takes on the bottle flipping craze with a bunch of increasingly tricky physics platforming puzzles. It's difficult and highly frustrating, but also addictive. When you begin to master the game, the sense of achievement is... | Read more »

Price Scanner via

Apple’s Thursday “Hello Again” Event A Largel...
KGI Securities analyst Ming-Chi Kuo, who has a strong record of Apple hardware prediction accuracy, forecasts in a new note to investors released late last week that a long-overdue redo of the... Read more
12-inch Retina MacBooks on sale for $100 off...
Amazon has 2016 12″ Apple Retina MacBooks on sale for $100 off MSRP. Shipping is free: - 12″ 1.1GHz Silver Retina MacBook: $1199.99 $100 off MSRP - 12″ 1.1GHz Gold Retina MacBook: $1199.99 $100 off... Read more
Save up to $600 with Apple refurbished Mac Pr...
Apple has Certified Refurbished Mac Pros available for up to $600 off the cost of new models. An Apple one-year warranty is included with each Mac Pro, and shipping is free. The following... Read more
PixelStyle Inexpensive Photo Editor For Mac W...
PixelStyle is an all-in-one Mac Photo Editor with a huge range of high-end filters including lighting, blurs, distortions, tilt-shift, shadows, glows and so forth. PixelStyle Photo Editor for Mac... Read more
13-inch MacBook Airs on sale for $100-$140 of...
B&H has 13″ MacBook Airs on sale for $100-$140 off MSRP for a limited time. Shipping is free, and B&H charges NY sales tax only: - 13″ 1.6GHz/128GB MacBook Air (sku MMGF2LL/A): $899 $100 off... Read more
2.8GHz Mac mini available for $988, includes...
Adorama has the 2.8GHz Mac mini available for $988, $11 off MSRP, including a free copy of Apple’s 3-Year AppleCare Protection Plan. Shipping is free, and Adorama charges sales tax in NY & NJ... Read more
21-inch 3.1GHz 4K on sale for $1379, $120 off...
Adorama has the 21″ 3.1GHz 4K iMac on sale $1379.99. Shipping is free, and Adorama charges NY & NJ sales tax only. Their price is $120 off MSRP. To purchase an iMac at this price, you must first... Read more
Check Apple prices on any device with the iTr...
MacPrices is proud to offer readers a free iOS app (iPhones, iPads, & iPod touch) and Android app (Google Play and Amazon App Store) called iTracx, which allows you to glance at today’s lowest... Read more
Apple, Samsung, Lead J.D. Power Smartphone Sa...
Customer satisfaction is much higher among smartphone owners currently subscribing to full-service wireless carriers, compared with those purchasing service through a non-contract carrier, according... Read more
Select 9-inch Apple WiFi iPad Pros on sale fo...
B&H Photo has select 9.7″ Apple WiFi iPad Pros on sale for up to $50 off MSRP, each including free shipping. B&H charges sales tax in NY only: - 9″ Space Gray 256GB WiFi iPad Pro: $799 $0 off... Read more

Jobs Board

*Apple* Retail - Multiple Positions- Towson,...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
Software Engineering Intern: Integration / QA...
Job Summary Apple is currently seeking enthusiastic interns who can work full-time for a minimum of 12-weeks between Fall 2015 and Summer 2016. Our software Read more
Software Engineering Intern: Frameworks at *...
Job Summary Apple is currently seeking enthusiastic interns who can work full-time for a minimum of 12-weeks between Fall 2015 and Summer 2016. Our software Read more
*Apple* Retail - Multiple Positions- Nashua,...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* Retail - Multiple Positions- Napervi...
Job Description:SalesSpecialist - Retail Customer Service and SalesTransform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.