11.04.2014 Views

Advanced MFC Programming

Advanced MFC Programming

Advanced MFC Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 2. Menu<br />

void CMenuDoc::OnFileClose()<br />

{<br />

CMenu menu;<br />

}<br />

menu.LoadMenu(IDR_MAINFRAME);<br />

AfxGetMainWnd()->SetMenu(&menu);<br />

AfxGetMainWnd()->DrawMenuBar();<br />

menu.Detach();<br />

In the above three member functions, we use a local variable menu to load the menu resource. It will be<br />

destroyed after the function exits. So before the variable goes out of scope, we must call function<br />

CMenu::Detach() to release the loaded menu resource so that it can continue to be used by the application.<br />

Otherwise, the menu resource will be destroyed automatically.<br />

Summary<br />

1) In order to execute commands, we need to handle message WM_COMMAND. In order to update user<br />

interfaces of menu, we need to handle message UPDATE_COMMAND_UI.<br />

1) To implement right-click menu, we need to first prepare a menu resource, then trap WM_RBUTTONDOWN<br />

message. Within the message handler, we can use CMenu type variable to load the menu resource, and<br />

call CMenu::TrackPopupMenu(…) to activate the menu and track mouse activities. Before the menu is<br />

shown, we can call functions CMenu::EnableMenuItem(…) and CMenu::CheckMenuItem(…) to set the<br />

states of the menu items.<br />

1) To add or remove a menu item dynamically, we need to call functions CMenu::InsertMenu(…) and<br />

CMenu::RemoveMenu(…).<br />

1) With function CMenu::SetMenuItemBitmaps(…), we can use bitmap images to implement checked and<br />

unchecked states for a menu item.<br />

1) A window’s standard menu can be obtained by calling function CWnd::GetMenu(), and the<br />

application’s system menu can be obtained by calling function CWnd::GetSysMenu(…).<br />

1) We can change a normal menu item to a bitmap menu item, a separator, or a sub-menu by calling<br />

function CMenu::ModifyMenu(…).<br />

1) Owner-draw menu can be implemented by setting MF_OWNERDRAW style then overriding functions<br />

CMenu::MeasureItem(…) and CMenu::DrawItem(…).<br />

1) We can change the whole menu attached to a window by calling function CWnd::SetMenu(…).<br />

56

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!