MFC List Control: How to use a context menu in a list control?
Q: How to use a context menu in a list control?
A:
- Create a menu in the resource editor.
<br><br> - Derive your own class from CListBox and insert the WM_CONTEXTMENU handler in the class.
<br><br> - Insert the following code in your 'OnContextMenu()' function:
Code:
void CMyListBoxCtl::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(MY_CREATED_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);
}
<br> - Create a member variable from your List Control and change the class name with your derived class.
<br><br>