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: ListView_SetColumnWidth
takes a column number and a width, and there are two special width values:
LVSCW_AUTOSIZE
, which sizes to content,LVSCW_AUTOSIZE_USEHEADER
, 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_AUTOSIZE
for every column.
0 comments