clistviewwinapi

Programmatically de-select all items in a ListView in Win32 API


I can't find a Win32 API way to programmatically clear out all current selections in a ListView control.

First of all, the ListView_SetCheckState macro only applies to special LVS_EX_CHECKBOXES ListView that I don't have.

Looking at ListView_SetItemState, it supports 4 bits, LVIS_CUT / LVIS_DROPHILITED / LVIS_FOCUSED / LVIS_SELECTED. It doesn't have an "UnSelected" value.

I don't want it to erase any existing LVIS_CUT / LVIS_FOCUSED flags that may be set on an item. But just as a test, I did the following with index=-1 (so all the items are affected) to completely erase all the data bits on a ListView including any selections:

ListView_SetItemState(hWndListView, -1, 0, NULL);

This didn't work and I still have my selections.


Solution

  • ListView_SetItemState() is the correct way. You need to set the mask parameter to LVIS_SELECTED to indicate you want to modify the "selected" bit, and set the data parameter to 0 to clear the bit.

    ListView_SetItemState(hWndListView, -1, 0, LVIS_SELECTED);