Question

I'm searching a way to determine a right-click on header of list ctrl to show context menu. I have a code example, but it doesnt work.

void ExDialog::OnContextMenu(CWnd* pWnd, CPoint point)
{
    CListCtrl* pLC = (CListCtrl*) GetDlgItem(IDC_EXAMPLE);
    CHeaderCtrl* pHC = pLC->GetHeaderCtrl();
    if (pWnd->GetSafeHwnd()==pHC->GetSafeHwnd())
    {
        CMenu menu;
        VERIFY(menu.LoadMenu(IDR_HEADERMENU));
        CMenu* pPopup = menu.GetSubMenu(0);
        ASSERT(pPopup != NULL);
        CWnd* pWndPopupOwner = pHC;
        pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, pWndPopupOwner);
    }
}
Was it helpful?

Solution

You get listview control there as argument, then you need to find header from there yourself: hit testing and/or comparing coordinates:

CListCtrl* pLC = (CListCtrl*) GetDlgItem(IDC_LIST1);
CHeaderCtrl* pHC = pLC->GetHeaderCtrl();
if (pWnd->GetSafeHwnd() == pLC->GetSafeHwnd()) // <<--- Not pHC!
{
    UINT nFlags = 0;
    pLC->HitTest(point, &nFlags);
    if(nFlags & LVHT_NOWHERE) // <<--- Header hits "nowhere"
    {
        CRect Position;
        pHC->GetWindowRect(Position);
        if(Position.PtInRect(point)) // <<--- point check 
        {
            CMenu menu;
            VERIFY(menu.LoadMenu(IDR_HEADERMENU));
            CMenu* pPopup = menu.GetSubMenu(0);
            ASSERT(pPopup != NULL);
            CWnd* pWndPopupOwner = pHC;
            pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, pWndPopupOwner);
        }
    }
}

OTHER TIPS

Looks good to me. Have you forgotten to put ON_WM_CONTEXTMENU() into the message-map for ExDialog()?

If that does not help, what do you see happening when you step through the function?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top