views:

371

answers:

3

How do I add a context menu in a list box in MFC? I don't see any WM_CONTEXTMENU handler in list box's properties. Any ideas?

EDIT: I followed this tutorial MFC List Control: How to use a context menu in a list control?. The tutorial says to derive my own class from CListBox which I did, but now how do I add list box of my derived class to the dialog?

A: 

Add a handler for your dialog window. That will generate this:

void YourDialogClass::OnContextMenu(CWnd* pWnd, CPoint point) {
  ...
}

pWnd will point to the window/control in which the user right clicked the mouse.

Nick D
but where do I add that? I mean there is no class for list box
hab
i can't see the class for list box in my source code. there are only two classes CDialog, CWinApp
hab
@Manzoor Ahmed, I edited my answer. The method will be placed in your dialog class.
Nick D
why should I add the handler in the dialog class, where is the list box class? please see my edit
hab
@Manzoor Ahmed, you don't really have to derive a class for every control that need a context menu. Goz wrote an example for you, try it.
Nick D
+2  A: 

Put an OnContextMenu handler in the parent class. Then add a popup menu

Edit To add the OnContextMenu handler, add an event handler to the PARENT window (ie not the list class). This is most easily done through the resource editor. Go to the properties page then go to the messages section. Then add a function for WM_CONTEXTMENU.

void CYourDialog::OnContextMenu(CWnd* pWnd, CPoint point)
{
    CListCtrl* pList = (CListCtrl*)GetDlgItem( ID_YOUR_LIST );

    if ( (CWnd*)pList == pWnd )
    {
     CMenu menu;
     // Create your menu items.

     int retVal = menu.TrackPopupMenu( TPM_LEFTALIGN | TPM_TOPALIGN | TPM_NONOTIFY | TPM_RETURNCMD, point.x, point.y, this );

     // Handle your returns here.
    }
}
Goz
A: 

If you followed the tutorial to derive you own class, make sure ON_WM_CONTEXTMENU() is added to the new class message map.

To add a list box of your derived class, you simply add a variable for your ListBox control and specify the variable class as your derived class.

However I think @Goz's answer is also a valid solution, and a simpler one.

djeidot