Menu Basics

zhaozj2021-02-17  40

Menu Basics

Let's start by defining a few terms. The menu bar that appears at the top of a window is an application's top-level menu, and the commands in it are called top-level menu items. The menu that appears when a top-level menu item is clicked is a drop-down menu, and items in that menu are referred to as menu items. Menu items are identified by integer values ​​called menu item IDs or command IDs. Windows also supports popup menus that look like drop-down menus but can be popped up anywhere on the screen. The context menu that appears when you right-click an object in the Windows shell is an example of a popup menu. Drop-down menus are actually popup menus that are submenus of an application's top-level Menu.

Most top-level windows also feature a system menu containing commands for restoring, moving, sizing, minimizing, maximizing, and closing the window. Windows provides this menu, which you display by clicking the left mouse button on the small icon in the window's title Bar, Clicking The Right Mouse Button in the body of the title bar, or pressing alt-spacebar.

MFC encapsulates menus and the actions that can be performed on them in the CMenu class. CMenu contains one public data member-an HMENU named m_hMenu that holds the handle of the corresponding menu-and several member functions that provide object-oriented wrappers around functions in the Windows API. CMenu :: TrackPopupMenu, for example, displays a context menu, and CMenu :: EnableMenuItem enables or disables a menu item. CMenu also contains a pair of virtual functions named DrawItem and MeasureItem that you can override if you want to create STYLIZED MENU ITEMS Containing Bitmaps and other graphical user interface elements.

You can create a menu in an MFC application in three ways: You can create a menu programmatically, piecing it together using CreateMenu, InsertMenu, and other CMenu functions You can initialize a series of data structures defining the menu's contents and create the menu with. .

The third method is far and away the most common because it allows you to define a menu off line using a resource editor or, if you'd prefer, a simple text editor. We'll focus on this method in the first half of the CHAPTER.

Creating a menu

The easiest way to create a menu is to add a menu template to your application's resource file A resource file is a scriptlike text file that defines an application's resources;. By convention, it is assigned the file name extension .rc and hence is often referred to as an RC file. A resource is a binary object such as a menu or an icon. Windows supports several types of resources, including (but not limited to) menus, icons, bitmaps, and strings. The resource compiler Rc.exe, which is provided with the Windows Software Development Kit (SDK) and is also part of Microsoft Visual C , compiles the statements in an RC file and links the resulting resources into the application's EXE file. Every resource is identified by a string or an integer ID such as "MyMenu" (string) or IDR_MYMENU (integer). Integer resource IDs are given human-readable names such as IDR_MYMENU by means of #define statements in a header file. Once a resource is compiled and linked into an EXE, it can Be loaded with a Simple function call.

A menu template contains all the information the resource compiler needs to create a menu resource, including the menu's resource ID, the names of the menu items, and the IDs of the menu items. The menu template in Figure 4-1 comes from a project created by Visual C 's MFC AppWizard. It defines a single menu resource consisting of a top-level menu and four submenus-File, Edit, View, and Help. IDR_MAINFRAME is the menu's resource ID. PRELOAD and DISCARDABLE are resource attributes. PRELOAD tells Windows to load the menu resource into memory when the application starts. DISCARDABLE allows Windows to discard the resource if the memory it occupies is needed for other purposes. (If it's needed again, a discarded resource can be reloaded from the application's EXE file.) PRELOAD And Discardable Aread Windows and has no Impact on Either The Performance or Behavior of 32-bit Applications.figure 4-1. a menu template generated by the MFC AppWizard.

IDR_MAINFRAME MENU PRELOAD DISCARDABLE

Begin

Popup "& file"

Begin

Menuitem "& new / tctrl n", id_file_new

Menuitem "& Open ... / TCTRL O", ID_FILE_OPEN

Menuitem "& Save / TCTRL S", ID_FILE_SAVE

Menuitem "Save & As ...", ID_FILE_SAVE_AS

Menuitem Separator

Menuitem "Recent File", ID_FILE_MRU_FILE1, GRAYED

Menuitem Separator

Menuitem "E & XIT", ID_APP_EXIT

End

Popup "& Edit"

Begin

Menuitem "& undo / tctrl z", id_edit_undo

Menuitem Separator

Menuitem "Cu & T / TCTRL X", ID_EDIT_CUT

Menuitem "& Copy / TCTRL C", ID_EDIT_COPY

Menuitem "& Paste / TCTRL V", ID_EDIT_PASTEEND

POPUP "& view"

Begin

Menuitem "& Toolbar", ID_View_toolbar

Menuitem "& status bar", id_view_status_bar

End

Popup "& Help"

Begin

Menuitem "& About MyApp ...", ID_APP_ABOUT

End

End

The statements between the opening and closing BEGIN and END statements define the contents of the menu, with POPUP statements defining top-level menu items and the associated submenus. The BEGIN and END statements following POPUP statements bracket MENUITEM statements defining the items in the submenus. The special MENUITEM SEPARATOR statement adds a thin horizontal line to the menu; it's used to provide visual separation between groups of menu items The ampersands in the text of the menu items identify shortcut keys the user can press in combination with the Alt key to display. submenus and select items from submenus. in this example, the File-Exit command can be selected by pressing Alt-F and then X. Windows underlines the F in "File" and the x in "Exit" so that they're easily identifiable AS Shortcut Keys. If Two or More Assigned The Same Shortcut Key, The Shortcut Cycles Among The Menu Items and No Selection is Made Until The Enter Key Is Pressed.

An ellipsis (...) in the text of a menu item indicates that further input is required after the item is selected. If the user selects Save, the document is saved immediately. But if the user selects Save As, a dialog box is displayed instead. To be consistent with other Windows applications, use an ellipsis for any menu item whose action is deferred until subsequent input is received from the user. If an item in the top-level menu executes a command instead of displaying a submenu, the Text of the item should Be Followed with an Exclamation Mark, As INDR_MAINFRAME MENU PRELOAD DISCARDABLE

Begin

Popup "& file"

[...]

Popup "& Edit"

[...]

POPUP "& view"

[...]

Popup "& Help"

[...]

Menuitem "E & XIT!", ID_APP_EXIT

End

It's legal to include MENUITEM statements in top-level menus this way, but these days it's considered bad form. And it's likely to surprise your users, most of whom are accustomed to seeing top-level menu items display submenus rather than take action themselves.

The ID_ values ​​following the menu item names in the MENUITEM statements are command IDs. Every menu item should be assigned a unique command ID because it is this value that identifies the menu item to your application when the user makes a selection. By convention, IDs are defined with #define statements, and each is given the name ID_ or IDM_ followed by an item name spelled in capital letters. MFC's afxres.h header file defines ID_ values ​​for commonly used commands such as File-New and Edit-Paste. When you write document / view applications, using the predefined IDs automatically connects certain menu items to handling functions the framework provides. In nondocument / view applications, use of the predefined IDs is optional.Valid values ​​for menu item IDs range from 1 through 0xEFFF, but MFC Technical Note # 20 Recommends Restricting The Range to 0x8000 THROUGH 0xDFFF. IDS Equal to 0xF000 And Higher Are Reserved for Windows-Specifically, for Items in the System Menu. The Range 0xE000 To 0xEFFF is reserved for MFC. In practice, it's perfectly safe to use values ​​lower than 0x8000, and in fact, restricting item IDs to the range 1 through 0x7FFF sidesteps a nasty bug in Windows 95 that affects owner-draw menu items. This bug is EXPLAINED-AND WORK-AROUNDS Are Presented-later in this chapter.

THE TEXT FOLLOWING THE TAB Character in Some of the Menu Items (for Example, The "Ctrl O" in "Open ... / TCTRL O") Identifies An Accelerator. An Accelerator Is A Key Or Combination of Keys That, When Pressed, has the same effect as selecting a menu item. Commonly used accelerators include Ctrl-X for Edit-Cut, Ctrl-C for Edit-Copy, and Ctrl-V for Edit-Paste. Text strings denoting accelerator keys are preceded by tab characters for alignment purposes. The default font used in menus is proportionally spaced, so it's futile to try to align menu text with spaces.When you define a menu item with MENUITEM, you also have the option of specifying the item's initial state. The GRAYED keyword accompanying the File-Recent File command in Figure 4-1 disables the menu item so that it can not be selected. A disabled item is "grayed out" as a visual reminder that it is disabled. grayed menu text is displayed in the system color Color_Graytext, Which defaults to gray, with a Thin Border Added to Provide A THR ee-dimensional look. Another optional keyword is CHECKED, which places a check mark beside a menu item. Although common in Windows applications written in C using the SDK, menu item state specifiers are rarely used in MFC applications because the framework provides a powerful mechanism .

Loading and displaming a menu

AT Run Time, A Menu Resource Needs to Be loaded and attachd to a window .hen the window is displayed, The menu will also be displayed.

One way to attach a menu to a window is to pass the menu's resource ID to CFrameWnd :: Create The following statement creates a frame window and attaches the menu whose resource ID is IDR_MAINFRAME:. Create (NULL, _T ( "My Application") WS_OVERLAPPEDWINDOW,

RectDefault, NULL, MakeintResource (IDR_MAINFRAME);

The sixth argument to Create identifies the menu resource. The MAKEINTRESOURCE macro converts an integer resource ID to an LPTSTR data type ID compatible with functions that expect string-based resource IDs. When the window appears on the screen, the menu will be visible just below The Title Bar.

A Second Method Involves The CFrameWnd :: LoadFrame Function. Given a Resource ID, LoadFrame Creates A Frame Window And Attaches A Menu, Much Like Create. The Statement.

LoadFrame (IDR_MAINFRAME, WS_OVERLAPPEDWINDOW, NULL, NULL);

creates a window and attaches the menu IDR_MAINFRAME. Some MFC programs-particularly wizard-generated applications-use LoadFrame instead of Create because LoadFrame will load icons and other resources, too. MAKEINTRESOURCE is not required in this example because it's built into LoadFrame.

YET Another Method for Loading A Top-Level Menu and Attaching It To A Window Is To Construct A CMenu Object, Call Cmenu :: LoadMenu To Load The Menu Resource, And Call CWnd :: SetMenu, Like THIS:

CMenu Menu;

Menu.LoadMenu (idR_mainframe);

SetMenu (& Menu);

Menu.detach ();

In this example, CMenu :: Detach is called to detach the menu from the CMenu object so that the menu will not be destroyed prematurely when menu goes out of scope. The CMenu class helps guard against resource leaks by calling CMenu :: DestroyMenu from its destructor. As a rule, a menu loaded with LoadMenu should be destroyed with DestroyMenu before the application that loaded the menu terminates. However, a menu attached to a window is automatically destroyed when the window is destroyed, so detaching a menu from a CMenu object after attaching it to a window will not cause a resource leak unless the menu is later detached from the window without a subsequent call to DestroyMenu.The SetMenu technique offers no advantage over simply passing the menu ID to Create or LoadFrame when a program contains Just One Menu, But It's, But It's.. Suppose You Want To Write An Application That You Want To Write An Application That OR Long Menus. Here's One Way To Go About IT . First, create two menu resources-one for the short menus, another for the long. At startup, load the menu resources into CMenu data members named m_menuLong and m_menuShort. Then choose the menu type based on the value of a BOOL data member named M_BshortMenu, Which is True IF Short Menus Are SELECTED AND FALSE IF THEO'RE NOT. Here's What The Window's Construction Might Look Like:

Create (NULL, _T ("My Application");

M_Menulong.LoadMenu (IDR_longmenu);

m_menushort.loadmenu (idR_shortmenu);

SetMenu (m_bshortmenu? & M_menushort: & m_menulong);

In response to a command from the user, The Following Code Would Switch from Long Menus to Short Menus:

M_BshortMenu = TRUE;

SetMenu (& m_menushort); DrawMenuBar ();

And these Statements Would Switch Back to Long Menus:

m_bshortmenu = false;

SetMenu (& M_Menulong);

Drawmenubar ();

CWnd :: DrawmenuBar Redraws The Menu Bar To Reflect The Change. You Should Always Follow Calls to Drawmenu with Calls to DrawmenuBar Unsible The screen.

What about code to delete the menus, since only one will be attached to a window when the application ends? If m_menuLong and m_menuShort are data members of the frame window class, their destructors will be called when the frame window is destroyed and the menus associated With Them Will Also Be deleted. Therefore, Explicit Calls to DestroyMenu Aren't Required.

Responding to Menu Commands

When the user pulls down a menu, the window to which the menu is attached receives a series of messages. Among the first to arrive is a WM_INITMENU message notifying the window that a top-level menu item was selected. Before a submenu is displayed, the window receives a WM_INITMENUPOPUP message. Windows programs sometimes take this opportunity to update the submenu's menu items-for example, putting a check mark next to the Toolbar item in the View menu if the application's toolbar is displayed or unchecking the menu item if the toolbar is currently hidden. As the highlight travels up and down the menu, the window receives WM_MENUSELECT messages reporting the latest position in the menu. in SDK-style programs, WM_MENUSELECT messages are sometimes used to display context-sensitive menu help in a status bar.

The most important message of all is the WM_COMMAND message sent when the user selects an item from the menu. The low word of the message's wParam parameter holds the item's command ID. SDK programmers often use switch-case logic to vector execution to the appropriate handling routine, but MFC provides a better way. An ON_COMMAND statement in the message map links WM_COMMAND messages referencing a particular menu item to the class member function, or command handler, of your choice. The following message-map entry tells MFC to call OnFileSave when THE ID_FILE_SAVE MENU ITEM IS SELECTED: ON_COMMAND (ID_FILE_SAVE, ONFILESAVE)

Other items in the file menu might be mapped like this:

ON_COMMAND (ID_FILE_NEW, ONFILENEW)

ON_COMMAND (ID_FILE_OPEN, ONFILEOPEN)

ON_COMMAND (ID_FILE_SAVE, ONFILESAVE)

ON_COMMAND (ID_FILE_SAVE_AS, ONFILESAVEAS)

ON_COMMAND (ID_FILE_EXIT, ONFILEEXIT)

No ONFileNew Will Be Activated WHEN File-New Is SELECTED, ONFILEOPEN WILL BE CALLED WHEN FILE-OPEN IS SELECTED, AND SO ON.

Command Handlers Take No Arguments and Return No Values. The onfileExit Function, for Example, IS TYPICLY IMPLEMENTED LIKE THIS

Void cmainwindow :: onfileexit ()

{

Postmessage (WM_Close, 0, 0);

}

This command handler terminates the application by posting a WM_CLOSE message to the application's main window. This message ultimately ends the application by causing a WM_QUIT message to appear in the application's message queue.

You can name command handlers whatever you like. There are no naming criteria as there are for WM_ message handlers. Handlers for WM_PAINT and WM_CREATE must be named OnPaint and OnCreate unless you care to rewrite MFC's ON_WM_PAINT and ON_WM_CREATE macros. But you could just as easily Have Written The Message-map entries for ur file menu like this: on_command (id_file_new, createmeafile)

ON_COMMAND (ID_FILE_OPEN, OpenMeafile)

ON_COMMAND (ID_FILE_SAVE, SAVETHISFILE)

ON_COMMAND (ID_FILE_SAVE_AS, SAVETHISFILEUNDERANOTHERNAME)

ON_COMMAND (ID_FILE_EXIT, KILLTHISAPPANDDOITNOW)

Command Ranges

Sometimes it's more efficient to process a group of menu item IDs with a single command handler than to provide a separate member function for each ID. Consider a drawing application that contains a Color menu from which the user can choose red, green, or blue. Selecting a color from the menu sets a member variable named m_nCurrentColor to 0, 1, or 2 and subsequently changes the color of what the user draws on the screen. The message-map entries and command handlers for these menu items might be implemented as follows :

// in CMainWindow's Message Map

ON_COMMAND (ID_color_red, oncolorred)

ON_COMMAND (ID_COLOR_GREEN, ONCOLORGREEN)

ON_COMMAND (ID_COLOR_BLUE, ONCOLORBLUE)

Void cmainwindow :: oncolorred ()

{

m_ncurrentcolor = 0;

}

Void cmainwindow :: oncolorgreen ()

{

m_ncurrentcolor = 1;

}

Void cmainwindow :: oncolorblue ()

{

m_ncurrentcolor = 2;

}

This is not a terribly efficient way to process messages from the Color menu because each message handler does essentially the same thing. And the inefficiency would be compounded if the menu contained 10 or 20 different colors rather than just 3.

One way to reduce the redundancy in the command handlers for the Color menu is to map all three items to the same CMainWindow member function and retrieve the menu item ID with CWnd :: GetCurrentMessage, as shown below.// In CMainWindow's message map

ON_COMMAND (ID_COLOR_RED, ONCOLOR)

ON_COMMAND (ID_COLOR_Green, ONCOLOR)

ON_COMMAND (ID_COLOR_BLUE, ONCOLOR)

Void cmainwindow :: oncolor ()

{

UINT NID = (uint) loword (getCurrentMessage () -> wparam);

m_ncurrentcolor = NID _ ID_COLOR_RED;

}

This approach works just fine as long as the command IDs constitute a contiguous range beginning with ID_COLOR_RED, but it's an imperfect solution because it relies on the value of wParam. If the meaning of the wParam parameter accompanying WM_COMMAND messages changes in a future release of Windows (as it did between Windows 3.1 and Windows 95), you might have to modify this code to get it to work properly. and even though you've reduced the number of command handlers from three to one, you're still adding three separate Entries to the class's message map at a cost of 24 bytes each.

A better solution is the MFC ON_COMMAND_RANGE macro, which maps a range of contiguous command IDs to a common handling function. Assuming ID_COLOR_RED is the lowest value in the range and ID_COLOR_BLUE is the highest, ON_COMMAND_RANGE allows you to rewrite the code for the Color menu like THIS:

// in CMainWindow's Message Map

ON_COMMAND_RANGE (ID_COLOR_RED, ID_COLOR_BLUE, ONCOLOR)

Void CMainWindow :: ONCOLOR (UINT NID)

{

m_ncurrentcolor = NID _ ID_COLOR_RED;

}

When OnColor is called because the user chose an item from the Color menu, nID contains ID_COLOR_RED, ID_COLOR_GREEN, or ID_COLOR_BLUE. One simple statement sets m_nCurrentColor to the proper value, no matter which menu item was selected.Updating the Items in a Menu

In many applications, menu items must be constantly updated to reflect internal states of the application or its data. When a color is selected from a Color menu, for example, the corresponding menu item should be checked or bulleted to indicate which color is currently selected . An application that features an Edit menu with Cut, Copy, and Paste commands should disable the Cut and Copy menu items when nothing is selected and disable the Paste menu item when the clipboard is empty. Menus are more than just lists of commands. Deployed Properly, They Provide Visual Feedback To The User About The Current State of The Application And Make Clear What Commands Are (and is not) Available at Any Given Moment.

Windows programmers have traditionally taken one of two approaches to keeping menu items up to date The first approach is illustrated by the following code sample, which is a modified version of the OnColor function presented in the previous section.:

Void CMainWindow :: ONCOLOR (UINT NID)

{

Cmenu * pmenu = getMenu ();

Pmenu-> CheckmenuItem (m_ncurrentcolor id_color_red, mf_unchecked);

Pmenu-> CheckmenuItem (NID, MF_CHECKED);

m_ncurrentcolor = NID _ ID_COLOR_RED;

}

In this example, the Color menu is updated the moment an item is selected. First CMenu :: CheckMenuItem is called with an MF_UNCHECKED flag to uncheck the item that's currently checked. Then CheckMenuItem is called with an MF_CHECKED flag to place a check mark by the item that was just selected. The next time the Color menu is pulled down, the check mark will identify the current color.The second approach is to move the code that updates the menu to an OnInitMenuPopup handler that's activated in response to WM_INITMENUPOPUP messages. This strategy positions the check mark each time the Color menu is pulled down, just before the menu is actually displayed OnInitMenuPopup receives three parameters:. a CMenu pointer referencing the submenu that's about to be displayed, a UINT value holding the submenu's 0-based index in The Top-Level Menu, And A Bool Value That's Nonzero if The Message Pertains To The System Menu Instead of a Submenu. Here's What An OninitMenupopup Handler for the Color Men u Might Look Like. Color_Menu_index is an index specifying the color menu's position in the top-level menu:

// in CMainWindow's Message Map

ON_WM_INITMENUPOPUP ()

Void CMainWindow :: OnNitMenupopup (cmenu * ppopupmenu, uint nindex,

Bool Bsysmenu)

{

IF (! bsysmenu& (nindex == color_meu_index)) {

PpopupMenu-> CheckMenuItem (id_color_red, mf_unchecked);

Ppopupmenu-> CheckMenuItem (ID_COLOR_GREEN, MF_UNCHECKED);

Ppopupmenu-> CheckMenuItem (ID_COLOR_BLUE, MF_UNCHECKED);

PpopupMenu-> CheckMenuItem (m_ncurrentcolor id_color_red,

MF_CHECKED);

}

}

This method is more robust than the first because it decouples the code that processes commands from the code that updates the menu. Now any function anywhere in the application can change the drawing color, and the menu will be updated automatically the next time it's displayed. MFC provides a similar but more convenient mechanism for keeping menu items updated. Through ON_UPDATE_COMMAND_UI macros in the message map, you can designate selected member functions to serve as update handlers for individual menu items. When the user pulls down a menu, MFC traps the ensuing WM_INITMENUPOPUP message and calls the update handlers for all the items in the menu. Each update handler is passed a pointer to a CCmdUI object whose member functions can be used to modify the menu item. and because the CCmdUI class is not specific to any particular TYPE OF User Interface (UI) Element, The Same Update Handler That Serves A Menu Item CAN Serve Toolbar Buttons and Other Ui Objects, Too. Abstracting Ui Updat ES in this Way Simplifier The Program Logic and Helps make An Application Independent of The Operating System It's Written for.

Here's how to shutrite the code for the color menu to take Advantage of Update Handlers:

// in CMainWindow's Message Map

ON_COMMAND_RANGE (ID_COLOR_RED, ID_COLOR_BLUE, ONCOLOR)

ON_UPDATE_COMMAND_UI (ID_COLOR_RED, ONUPDATECOLORRED)

ON_UPDATE_COMMAND_UI (id_color_green, onupdatecolorgreen)

ON_UPDATE_COMMAND_UI (ID_COLOR_BLUE, ONUPDATECOLORBLUE)

Void CMainWindow :: ONCOLOR (UINT NID)

{

m_ncurrentcolor = NID _ ID_COLOR_RED;

}

Void CMainWindow :: OnUpdateColorred (ccmdui * pcmdui)

{

PCMDUI-> setCheck (m_ncurrentcolor == 0);

}

Void cmainwindow :: onupdatecolorgreen (ccmdui * pcmdui) {

PCMDUI-> SetCheck (m_ncurrentcolor == 1);

}

Void CMainWindow :: OnUpdateColorBlue (ccmdui * pcmdui)

{

PCMDUI-> SetCheck (m_ncurrentcolor == 2);

}

ON_UPDATE_COMMAND_UI connects menu items to update handlers just as ON_COMMAND connects menu items to command handlers. Now selecting a color from the Color menu will activate CMainWindow :: OnColor, and before the Color menu is displayed, each item's update handler will be called. The handlers shown here do their updating by calling CCmdUI :: SetCheck to check or uncheck the corresponding menu item Called with a nonzero value, SetCheck adds a check mark to the corresponding menu item;. called with a 0, it displays no check mark.

SetCheck is Just One of the ccmdui method a menu item. The Following Table Shows A Complete List, Along With A Description of Each Function's Effect ON A Menu Item.

FunctionDescriptionCCmdUI :: EnableEnables or disables a menu itemCCmdUI :: SetCheckChecks or unchecks a menu itemCCmdUI :: SetRadioBullets or unbullets a menu itemCCmdUI :: SetTextChanges the text of a menu item

. SetRadio works like SetCheck but adds or removes a bullet instead of a check mark SetRadio is one of those MFC functions that does not have a direct counterpart in the Windows API; the framework does some work behind the scenes to allow menu items to be bulleted rather than checked. Ideally, you'd use a bullet to indicate which item in a group of mutually exclusive menu items is currently selected and a check mark to indicate whether a feature is on or off. (in practice, check marks are frequently Used for Both.) Enable enables or disables a menu item, and settext allows you to change the text of the menu item on the fly.update ranges

For updating groups of menu items with a single update handler, MFC provides the ON_UPDATE_COMMAND_UI_RANGE macro, which is to ON_COMMAND_RANGE as ON_UPDATE_COMMAND_UI is to ON_COMMAND To understand how ON_UPDATE_COMMAND_UI_RANGE is used, let's revisit the Color menu and assume that it contains eight color choices:. Black , blue, green, cyan, red, magenta, yellow, and white, in that order. The corresponding menu item IDs are ID_COLOR_BLACK through ID_COLOR_WHITE. Let's also assume that we want to put a bullet by the current color. Here's the most concise way TO DO IT.

// in CMainWindow's Message Map

ON_COMMAND_RANGE (ID_COLOR_BLACK, ID_COLOR_WHITE, ONCOLOR)

ON_UPDATE_COMMAND_UI_RANGE (ID_COLOR_BLACK, ID_COLOR_WHITE,

OnUpdateColorui)

Void CMainWindow :: ONCOLOR (UINT NID)

{

M_ncurrentcolor = NID _ ID_COLOR_BLACK;

}

Void CMainWindow :: onupdatecolorui (ccmdui * pcmdui)

{

PCMDUI-> Setradio (PCMDUI-> M_NID - ID_COLOR_BLACK ==

m_ncurrentcolor;

}

m_nID is a public data member of CCmdUI that holds the ID of the menu item for which the update handler was called. By comparing m_nID minus ID_COLOR_BLACK to m_nCurrentColor and passing the result to SetRadio, you can ensure that only the current color is bulleted.Just how useful is MFC's command-update mechanism? Later in this chapter, we'll develop a sample program that uses two identical Color menus-one that's invoked from a top-level menu and another that's invoked from a right-click context menu. The same command and update handler will serve both menus, and no matter how a color is selected, both menus will be updated to match-with one line of code no less. It's hard to imagine how updating menu items could be any easier.

Keyboard Accelerators

As you design your application's menus, you have the option of using keyboard accelerators to assign shortcut keys to any or all of the menu items. An accelerator produces a WM_COMMAND message just as making a menu selection does. Adding keyboard accelerators to your application is simplicity itself. You create an accelerator table resource-a special resource that correlates menu item IDs to keys or combinations of keys-and load the resource into your program with a function call. If the application's main window is a frame window, Windows and the framework DO The REST, AUTOMATILLY TRAPPING PRESSES OF Accelerator Keys and Notify Your Application with WM_Command Messages.

An Accelerator Table Resource IS defined by an accelerators block in an rc file. Here is the general format:

ResourceId Accelerators

Begin

End

ResourceID is the accelerator table's resource ID The statements between BEGIN and END identify the accelerator keys and the corresponding menu item IDs The MFC AppWizard generates accelerator tables using the following format:.. IDR_MAINFRAME ACCELERATORS PRELOAD MOVEABLE

Begin

"N", ID_FILE_NEW, VIRTKEY, CONTROL

"O", id_file_open, virtkey, control

"S", id_file_save, virtkey, control

"Z", id_edit_undo, Virtkey, Control

"X", id_edit_cut, virtkey, control

"C", id_edit_copy, Virtkey, Control

"V", id_edit_paste, virtkey, control

VK_BACK, ID_EDIT_UNDO, VIRTKEY, ALT

VK_DELETE, ID_EDIT_CUT, VIRTKEY, SHIFT

VK_INSERT, ID_EDIT_COPY, VIRTKEY, CONTROL

VK_INSERT, ID_EDIT_PASTE, VIRTKEY, SHIFT

End

In this example, IDR_MAINFRAME is the accelerator table's resource ID. PRELOAD and MOVEABLE are load options that, like the equivalent keywords in MENU statements, have no effect in the Win32 environment. Each line in the table defines one accelerator. The first entry in each line defines the accelerator key, and the second identifies the corresponding menu item. The VIRTKEY keyword tells the resource compiler that the first entry is a virtual key code, and the keyword following it-CONTROL, ALT, or SHIFT-identifies an optional modifier key In this Example, Ctrl-N IS An Accelerator for File-New, Ctrl-O Is An Accelerator for File-Open, Ando On. The Edit Menu's undo, CUT, COPY, AND PASTE Functions Each Have Two Accelerators Defined: Ctrl -Z and alt-backspace for undo, ctrl-x and shift-del for copy, and ctrl-v and shift-ins for paste.like menus, keyboard accelerators must be loading and attlerators must be loading and attelerators To a window before they'll do anything. for a frame window, loading CCELTABLE DOES The Loading and attaching in One Step:

LoadAcceltable (MakeintResource (iDR_mainframe);

LoadFrame Also Does The Job Nicely. In Fact, The Same Function Call That Loads The Menu Also Loads The Accelerator Table If The Two Resources Share The Same ID:

LoadFrame (IDR_MAINFRAME, WS_OVERLAPPEDWINDOW, NULL, NULL);

For accelerators to work, the message loop must incrude a call to the API Function :: TranslateAccelerator, as shown here:

While (GetMessage (& MSG, NULL, 0, 0)) {

IF (! TranslateAccelerator (HWnd, Haccel, & MSG)) {

TranslateMessage (& MSG);

DispatchMessage (& MSG);

}

}

MFC's CFrameWnd class handles this part for you. Specifically, it overrides the virtual PreTranslateMessage function that it inherits from CWnd and calls :: TranslateAccelerator if it sees an accelerator table has been loaded-that is, if the frame window's m_hAccelTable data member contains a non -NULL accelerator table handle. Not surprisingly, LoadAccelTable loads an accelerator resource and copies the handle to m_hAccelTable. LoadFrame does the same by calling LoadAccelTable.Accelerators must be handled differently when loaded for nonframe windows that lack the accelerator support in CFrameWnd. Suppose you derive A Custom Window Class from CWnd and Want To Use Accelerators, Too. Here's How you'd Go About IT:

Add an m_hAccelTable data member (type HACCEL) to the derived class. Early in your application's lifetime, use the API function :: LoadAccelerators to load the accelerator table. Copy the handle returned by :: LoadAccelerators to m_hAccelTable. In the window class, override PreTranslateMessage and call :: TranslateAccelerator with the handle stored in m_hAccelTable. Use the value returned by :: TranslateAccelerator as the return value for PreTranslateMessage so that the message will not be translated and dispatched if :: TranslateAccelerator has dispatched it already. Here's how it Looks in cotE:

// in CMainWindow's Constructor

m_hacceltable = :: loadAccelerators (AfxGetInstanceHandle (),

MakeintResource (iDR_accelerators);

// PretranslateMessage Override

Bool CMainWindow :: PretranslateMessage (MSG * PMSG)

{

IF (CWnd :: PretranslateMessage (PMSG))

Return True;

Return ((m_hacceltable! = null) &&&

:: TranslateAccelerator (M_HWND, M_HACCELTABLE, PMSG);

}

With this framework in place, a CWnd-type window will use accelerators just as a frame window does. Note that accelerators loaded with :: LoadAccelerators (or LoadAccelTable) do not need to be deleted before termination because Windows deletes them automatically.Using accelerators to provide shortcuts for commonly used menu commands is preferable to processing keystroke messages manually for two reasons. The first is that accelerators simplify the programming logic. Why write WM_KEYDOWN and WM_CHAR handlers if you do not have to? The second is that if your application's window contains child windows and a child window has the input focus, keyboard messages will go to the child window instead of the main window. (Child windows are discussed in Chapter 7.) As you learned in Chapter 3, keyboard messages always go to the Window with the input focus. But when, windows makess sales os, wm_command message goes to the main window even if one of its children Has T He INPUT FOCUS.

Accelerators are so useful for trapping keystrokes that they're sometimes used apart from menus. If you want to be notified any time the Ctrl-Shift-F12 combination is pressed, for example, simply create an accelerator for that key combination with a statement like This One:

VK_F12, ID_CTRL_SHIFT_F12, VIRTKEY, Control, Shift

Then map the accelerator to a class member function by Adding an

ON_COMMAND (id_ctrl_shift_f12, oncTrshiftf12)

Entry to the Message Map. Presses of Ctrl-Shift-F12 Will Thereafter Activate OnCtrlshiftf12, Even IF No Menu Item is Assigned The ID iD_CTRL_SHIFT_F12.

转载请注明原文地址:https://www.9cbs.com/read-30675.html

New Post(0)