( IDE : Visual C++ 6.0 )
I want to use the list control to create a program like Windows Task Manager.
It adds information (item) of the process received through api and displays it through list control.
What I want to do is to right-click on a specific item and a dialog box will appear like a real task manager.
As a result of searching, it seems to use OnContextMenu(CWnd*, CPoint) function, but it does not understand how it works.
I'd like you to provide a simple example.
Thank you :)
This is a working sample extracted from a project of mine. Please take note, that this code is working on VS'15 and likely also on VS'10. I do not have the 1998 version... it's been 20 years already.
I left some comments in the code. Please read up on these.
CMenu m_Menu; //Class member
m_Menu.CreateMenu(); //Call this once only (I do it in PreSubclassWindow)
//class CMenuListCtrl : public CListCtrl
void CMenuListCtrl::OnContextMenu(CWnd *pWnd, CPoint ptMousePos)
{
//Some people might use a keyboard and not the mouse
if (ptMousePos.x == -1 && ptMousePos.y == -1)
{
auto nSelectedItem = GetSelectionMark(); //Get the selected item in the CListCtrl
if (nSelectedItem == -1)
return;
//Find the position
CRect itemRect;
GetItemRect(nSelectedItem, &itemRect, LVIR_BOUNDS);
ClientToScreen(&itemRect);
ptMousePos.x = itemRect.left + (itemRect.Width() / 10); //Some offset to display the menu user-friendly
ptMousePos.y = itemRect.top + itemRect.Height() / 2;
}
CPoint hitPoint = ptMousePos;
ScreenToClient(&hitPoint);
//Fix header pop-up bug
CHeaderCtrl *pHeader = GetHeaderCtrl();
HDHITTESTINFO hitTestHeader = {0};
hitTestHeader.pt = hitPoint;
//The header doesn't need a context-menu, the item does
if (pHeader->HitTest(&hitTestHeader) != -1)
return;
UINT uFlags = 0;
HitTest(hitPoint, &uFlags);
if (uFlags & LVHT_NOWHERE)
return;
//Get the previously created menu
CMenu *pPopUp = nullptr;
pPopUp = m_Menu.GetSubMenu(0);
if (pPopUp)
pPopUp->TrackPopupMenu(TPM_LEFTALIGN, ptMousePos.x, ptMousePos.y, this);
}
In order to display the menu, you have to create one first.
CMenu submenu;
submenu.CreatePopupMenu();
submenu.AppendMenuW(MF_STRING, IDC_COPY_POPUP, L"&Copy");
submenu.AppendMenuW(MF_SEPARATOR);
submenu.AppendMenuW(MF_STRING, IDC_DELETE_POPUP, L"&Delete");
m_Menu.AppendMenuW(MF_POPUP, reinterpret_cast<UINT_PTR>(submenu.m_hMenu), L"");
submenu.Detach();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.