How can I programmatically resize a listview column to fit its contents?

Raymond Chen

Sven wanted to know if there is a listview message to resize a column to fit its contents.

Sure there is. In fact, the default Ctrl+Num+ handler uses that message.

Take our scratch program and make these changes:

OnCreate(HWND hwnd, LPCREATESTRUCT lpcs)
  g_hwndChild = CreateWindow(WC_LISTVIEW, NULL,
        0, 0, 0, 0, hwnd, (HMENU)1, g_hinst, 0);
  col.mask = LVCF_TEXT | LVCF_WIDTH; = 200;
  col.pszText = TEXT("Name");
  ListView_InsertColumn(g_hwndChild, 0, &col);
  LVITEM item;
  item.mask = LVIF_TEXT;
  item.iSubItem = 0;
  item.pszText = TEXT("Alpha");
  ListView_InsertItem(g_hwndChild, &item);
  item.pszText = TEXT("Beta");
  ListView_InsertItem(g_hwndChild, &item);
  item.pszText = TEXT("Gamma");
  ListView_InsertItem(g_hwndChild, &item);
  item.pszText = TEXT("Delta");
  ListView_InsertItem(g_hwndChild, &item);

  ListView_SetColumnWidth(g_hwndChild, 0, LVSCW_AUTOSIZE);
  return TRUE;

The first part of the code just creates a listview control in report mode, inserts a column called “Name”, then fills it with some dummy data.

The money is in the last line: List­View_Set­Column­Width takes a column number and a width, and there are two special width values:

  • LVSCW_AUTO­SIZE, which sizes to content,
  • LVSCW_AUTO­SIZE_USE­HEADER, which sizes to content and the header, with the bonus feature that if you are adjusting the width of the last column, then it extends to the remaining width in the listview.

The handler for the Ctrl+Num+ keyboard shortcut simply loops through all the columns and uses LVSCW_AUTO­SIZE for every column.


Discussion is closed.

Feedback usabilla icon