列表框宽度大小取决于文本长度

时间:2009-12-11 17:13:35

标签: mfc width clistbox

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

我想使窗口和列表框宽度根据列表框条目长度(字符数)动态更改。

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

这样做的最佳方式是什么?

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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  

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

答案 2 :(得分:0)

试试这个:

int maxcol = ((CHeaderCtrl*)(listctrl.GetDlgItem(0)))->GetItemCount()-1;
for (int col = 0; col <= maxcol; col++)
{
    listctrl.SetColumnWidth(col, LVSCW_AUTOSIZE_USEHEADER);
}