How to force a CListCtrl to always have one item selected?

Aho picture Aho · Oct 25, 2012 · Viewed 7.7k times · Source

I want a CListCtrl to always have a selected item, like a collection of radio buttons.

I have used the styles: LVS_SHOWSELALWAYS|LVS_SINGLESEL

I have been looking for a style for this, but haven't been able to find this.

Answer

TDieckman picture TDieckman · Sep 13, 2013

Handle WM_LBUTTONDOWN. In a CListCtrl-derived class, add

MyListCtrl.cpp:

BEGIN_MESSAGE_MAP(CMyListCtrl, CListCtrl)
    ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()

void CMyListCtrl::OnLButtonDown(UINT nFlags, CPoint point)
{
    UINT uHitFlags;
    int nItem = HitTest(point, &uHitFlags);

    if (uHitFlags & LVHT_NOWHERE)
    {
        // eat the message by just returning
        return;
    }

    CListCtrl::OnLButtonDown(nFlags, point);
}

This will prevent the mouse click from going to the control and eat the message. You will still be able to remove the selection programmatically, but the user won't be able to click anywhere in the blank area below your items to remove the selection.