Topic : Menus
Author : Unknown
Page : << Previous 7  
Go to page :


the default menu will be resumed.

Three WM_COMMAND message handlers for commands ID_FILE_NEW, ID_FILE_OPEN and ID_FILE_CLOSE are generated using class wizard. The member functions are named OnFileNew, OnFileOpen and OnFileClose. In the first two functions, we change the mainframe menu to IDR_MAINFRAME_ACTIVE, and in the third function, we change the menu back to IDR_MAINFRAME:

void CMenuDoc::OnFileNew()
{

CMenu menu;

menu.LoadMenu(IDR_MAINFRAME_ACTIVE);

AfxGetMainWnd()->SetMenu(&menu);

AfxGetMainWnd()->DrawMenuBar();

menu.Detach();

}

void CMenuDoc::OnFileOpen()

{

CMenu menu;

menu.LoadMenu(IDR_MAINFRAME_ACTIVE);

AfxGetMainWnd()->SetMenu(&menu);

AfxGetMainWnd()->DrawMenuBar();

menu.Detach();

}

void CMenuDoc::OnFileClose()

{

CMenu menu;

menu.LoadMenu(IDR_MAINFRAME);

AfxGetMainWnd()->SetMenu(&menu);

AfxGetMainWnd()->DrawMenuBar();

menu.Detach();

}


In the above three member functions, we use a local variable menu to load the menu resource. It will be destroyed after the function exits. So before the variable goes out of scope, we must call function CMenu::Detach() to release the loaded menu resource so that it can continue to be used by the application. Otherwise, the menu resource will be destroyed automatically.

Summary

1) In order to execute commands, we need to handle message WM_COMMAND. In order to update user interfaces of menu, we need to handle message UPDATE_COMMAND_UI.

2) To implement right-click menu, we need to first prepare a menu resource, then trap WM_RBUTTONDOWN message. Within the message handler, we can use CMenu type variable to load the menu resource, and call CMenu::TrackPopupMenu(...) to activate the menu and track mouse activities. Before the menu is shown, we can call functions CMenu::EnableMenuItem(...) and CMenu::CheckMenuItem(...) to set the states of the menu items.

3) To add or remove a menu item dynamically, we need to call functions CMenu::InsertMenu(...) and CMenu::RemoveMenu(...).

4) With function CMenu::SetMenuItemBitmaps(...), we can use bitmap images to implement checked and unchecked states for a menu item.

5) A window's standard menu can be obtained by calling function CWnd::GetMenu(), and the application's system menu can be obtained by calling function CWnd::GetSysMenu(...).

6) We can change a normal menu item to a bitmap menu item, a separator, or a sub-menu by calling function CMenu::ModifyMenu(...).

7) Owner-draw menu can be implemented by setting MF_OWNERDRAW style then overriding functions CMenu::MeasureItem(...) and CMenu::DrawItem(...).

8) We can change the whole menu attached to a window by calling function CWnd::SetMenu(...).

Page : << Previous 7