![]() |
![]() |
|||||||
|
Login Change Info Logout
DOWNLOADS |
by Alan Oursland Adding a Popup MenuOne of the most useful controls in modern applications is the popup menu on right-clicking the mouse. We are going to add a popup menu to our application. First, we need to create a menu resource. Select Insert-Resource from the menu, select Menu, and press New. Right click on the IDR_MENU1 label and select Properties (see how useful that was). Change the name to IDR_POPUPMENU. You should also have an empty menu available for editing. Normal menu bars lay out their options horizontally, left to right. Popup menus lay out their components vertically, top to bottom. We need to create a menu pane for our popup menu. In the first menu cell type the label "Popup Top" and press Enter. Select "Popup Top" and our menu pane will appear below it. Type "&Close" into the pane. Enter "ID_POPUP_CLOSE" as the ID. Save your resource definitions. We have just created the resource definition for our popup menu. Now we have to make our application open it. Open ClassWizard (Ctrl-W or View-ClassWizard). Rebuild the database if asked. If a dialog pops up that asks you to associate a class with the new menu resource, you can associate the CMainFrame class with it. Verify that CMainFrame is selected as the class. We want to display the popup menu on a right mouse button up event, so locate WM_RBUTTONUP in the Messages list. Double click on it to add a message handler. Double click on the new method to edit it. Edit OnRButtonUp to look like this:
void CMainFrame::OnRButtonUp(UINT nFlags, CPoint point)
{
CMenu popupMenu;
popupMenu.LoadMenu(IDR_POPUPMENU);
CMenu* subMenu = popupMenu.GetSubMenu(0);
ClientToScreen(&point);
subMenu->TrackPopupMenu(0, point.x, point.y,
AfxGetMainWnd(), NULL);
CFrameWnd::OnRButtonUp(nFlags, point);
}
LoadMenu loads the menu resource. GetSubMenu gets the particular popup menu we are using to display the Close menu item. ClientToScreen translates the cursor's screen position to the window position. Finally, TrackPopupMenu actually opens the menu. Simple, right? Go ahead and run the program. You'll notice that our option is greyed out in the popup menu. We still need to hook it up to do something. Close the program and go back into ClassWizard. Verify that CMainFrame is still selected as your class. Under Object IDs, select ID_POPUP_CLOSE. Double click on COMMAND under Messages. This will create the member function OnPopupClose (don't change the name). Edit OnPopupClose to look like this:
void CMainFrame::OnPopupClose()
{
PostMessage(WM_CLOSE);
}
Now, when the Close option is selected, we will send a WM_CLOSE message to the application ourselves. Compile and run the program. The popup menu should be fully functional.
|
|
|
|||||||||||||||||||||||
|
Questions or Comments? devcentral AT iticentral DOT com PRIVACY POLICY |