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?
veronicasAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
kmurphy99Connect With a Mentor Commented:
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
0
 
waseemanisCommented:
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);
}
}
0
 
kmurphy99Commented:
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
0
 
veronicasAuthor Commented:
kmurphy99's answer is the best.
0
 
veronicasAuthor Commented:
Excellent!
0
All Courses

From novice to tech pro — start learning today.