March 9th, 2015

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

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:

BOOL
OnCreate(HWND hwnd, LPCREATESTRUCT lpcs)
{
  g_hwndChild = CreateWindow(WC_LISTVIEW, NULL,
        WS_CHILD | WS_VISIBLE | LVS_REPORT,
        0, 0, 0, 0, hwnd, (HMENU)1, g_hinst, 0);
  LVCOLUMN col;
  col.mask = LVCF_TEXT | LVCF_WIDTH;
  col.cx = 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.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.