1

我的应用程序有一个带有 ListBox 的窗口,其中填充了随时间变化的文本,因此 Listbox 条目可以有多个长度。

我想让窗口和列表框宽度根据列表框条目长度(字符数)动态变化。

例如,如果我的列表框有多个条目并且最大长度为 30 个字符,我想让窗口及其列表框的宽度大于一个最大长度为 20 个字符的窗口。

做这个的最好方式是什么?

4

3 回答 3

1

尝试这样的事情:

// find the longest item
CString longest;
for (int i = 0; i < m_list.GetCount(); ++i)
{
    CString temp;
    m_list.GetText(i, temp);
    if (temp.GetLength() > longest.GetLength())
        longest = temp;
}

// get the with of the longest item
CSize size = GetWindowDC()->GetTextExtent(longest);

// you need this to keep the current height
RECT rect;
m_list.GetWindowRect(&rect);

// change only width
int width = size.cx;
int height = rect.bottom - rect.top;
m_list.SetWindowPos(NULL, 0, 0, width, height, SWP_NOZORDER | SWP_NOMOVE);
于 2009-12-11T18:44:22.787 回答
0

尝试这个:

int maxcol = ((CHeaderCtrl*)(listctrl.GetDlgItem(0)))->GetItemCount()-1;
for (int col = 0; col <= maxcol; col++)
{
    listctrl.SetColumnWidth(col, LVSCW_AUTOSIZE_USEHEADER);
}
于 2009-12-12T20:10:37.960 回答
0

您使用的是什么编程平台?我猜是 .NET 和 VB。

放入一个方法来检查列表的内容并根据需要更改框和窗口的大小:

Dim intMaxLength As Integer = 20
For Each myItem As String In ListBox1.Items
    If Len(myItem) > intMaxLength Then  
       'Number of characters times number of pixels per character  
        ListBox1.Width = Len(myItem) * 10  
        'Me refers back to the form object  
        'Add a few extra pixels to give space around your listbox  
        Me.Width = Len(myItem) * 10 + 30  
    End If  
Next  

希望这能给你一个不错的起点。

于 2009-12-11T17:25:06.303 回答