Link to home
Start Free TrialLog in
Avatar of veronicas
veronicas

asked on

CListCtrl right click menu

I want to put a popup menu for my users when the right click on a CListCtrl.  I need to check if they are actually on an item, or in white space.  If they are on an item, a menu will be presented that says "Edit" or "Add".  If they are on white space, just "Add" will be present.

How can I do this?  Do I need 2 submenus?  How can I tell if an item is highlighted in the list?
Avatar of waseemanis
waseemanis

Derive a class from CListCtrl. Subclass your list control.
Now in the Class you can put in a message handler
  ON_WM_CONTEXTMENU()
and the function goes something like this :


void mylistctrl::OnContextMenu( CWnd*, CPoint point)
{

if (point.x == -1 && point.y == -1)
{
//keystroke invocation
CRect rect;
GetClientRect(rect);
ClientToScreen(rect);
point = rect.TopLeft();
point.Offset(5, 5);
}

CMenu menu;
VERIFY(menu.LoadMenu(ID_POPUP_MENU));
CMenu* pPopup = menu.GetSubMenu(0);
ASSERT(pPopup != NULL);
CWnd* pWndPopupOwner = this;
while (pWndPopupOwner->GetStyle() & WS_CHILD)                  pWndPopupOwner = pWndPopupOwner-GetParent();
pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, pWndPopupOwner);
}
}
Add a handler for a right click in the list, then add code like this:

CMenu menu;
VERIFY(menu.LoadMenu(IDR_SMENU));
CMenu* pPopup = menu.GetSubMenu(0);
      
int selected = m_listItems.GetNextItem(-1,LVNI_SELECTED);

if(selected <0) {
        pPopup->EnableMenuItem(ID_ITEMEDIT,MF_GRAYED);
      }
      
      RECT rect;
      GetWindowRect(&rect);
      CPoint mousepos;
      GetCursorPos(&mousepos);
      pPopup->TrackPopupMenu(NULL,mousepos.x,mousepos.y, this);

Ken
Avatar of veronicas

ASKER

kmurphy99's answer is the best.
ASKER CERTIFIED SOLUTION
Avatar of kmurphy99
kmurphy99

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Excellent!