创建列表视图后无法更改列表视图中的列宽

Unable to change column width in a listview after creating it

本文关键字:视图 列表 创建      更新时间:2023-10-16

在将一些项目添加到列表视图后,我需要使用 win32 api 更改列宽,因为垂直滚动条的宽度会导致显示水平滚动条,我想删除它。

ListView_SetColumnWidth()不会改变列的宽度。

//Column
int CreateColumn(HWND hwndLV, int iCol, char* Text, int iBreite)
{
LVCOLUMN lvc;
lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT ;
lvc.fmt=LVCFMT_LEFT;
lvc.cx = iBreite;
lvc.pszText =(LPWSTR)Text;  
lvc.iSubItem = iCol;
return ListView_InsertColumn(hwndLV, iCol, &lvc);
}
//item
int CreateItem(HWND hwndList, char*  Text)
{ 
LVITEM lvi = {0};
lvi.mask = LVIF_TEXT | LVCFMT_LEFT;
lvi.pszText = (LPWSTR)Text;
return ListView_InsertItem(hwndList, &lvi);
} 
//Some code ...
hwndList = CreateWindow(WC_LISTVIEW , L"" ,  WS_VISIBLE | WS_CHILD | LVS_REPORT | WS_BORDER  | WS_VSCROLL , 10 , 10 ,300 , 200, hwnd, NULL, GetModuleHandle(NULL), 0); 
SendMessage(hwndList,LVM_SETEXTENDEDLISTVIEWSTYLE,LVS_EX_FULLROWSELECT,LVS_EX_FULLROWSELECT); 
GetClientRect(hwndList , &rect);
CreateColumn(hwndList , 0 , (char*)L"HEADER" , rect.right );
//Some other codes for adding items here
ListView_SetColumnWidth(hwndList, 0,200); //Does not change the width

如何更改列的宽度?

对于初学者,您应该更改两个"创建"函数,如下所示(第二个与您的代码有很大不同(:

//Column
int CreateColumn(HWND hwndLV, int iCol, const wchar_t* Text, int iBreite)
{
LVCOLUMN lvc;
lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM; // You set iSubItem
lvc.fmt = LVCFMT_LEFT;
lvc.cx = iBreite;
lvc.pszText = const_cast<wchar_t*>(Text);
lvc.iSubItem = iCol;
return ListView_InsertColumn(hwndLV, iCol, &lvc);
}
//item
int CreateItem(HWND hwndList, wchar_t* Text, int nItem) // Must have an item ID!
{
LVITEM lvi; // Don't set to { 0, } as you immediately overwrite first item ...
lvi.mask = LVIF_TEXT; // LVCFMT_LEFT is just plain wrong, here!
lvi.pszText = Text;
lvi.iItem = nItem;    // Must set this value;
lvi.iSubItem = 0;
return ListView_InsertItem(hwndList, &lvi);
}

您不会向我们显示添加项的代码,但您需要为每个调用提供一个递增的nItem值。否则,您的项目将以相反的顺序显示!

我还假设您将非常量(即不是字符串文字(传递给CreateItem.如果没有,请更改它,使其类似于CreateColumn处理Text的方式。

希望这有帮助!