依赖于文本长度的列表框宽度大小

问题描述:

我的应用程序有一个带有ListBox的窗口,其中充满随时间变化的文本,因此Listbox条目可以有多个长度。依赖于文本长度的列表框宽度大小

我想使窗口和列表框宽度根据列表框条目长度(以字符数)动态更改。作为一个例子,如果我的列表框有几个条目,最大长度是30个字符,我想让窗口和列表框的宽度大于一个窗口的长度是20个字符。

这样做的最好方法是什么?

您使用的是哪种编程平台?我猜测.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 

希望这给你一个体面的起点。

+0

MFC是托管C++ – 2009-12-11 17:27:42

+0

这改变了一切。我不是C++的人。也许别人可以帮助你。 ;) – Brad 2009-12-11 17:37:59

尝试这样:

// 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); 
+0

谢谢。这似乎是一个好方法。我会尽快回家。 – eniac 2009-12-11 19:04:19

+2

您可能需要在每个字符串上调用GetTextExtent。对于比例字体,短的字符串可能比较长的字符串更宽。 – 2009-12-11 19:21:32

+0

您需要确保使用列表框的设备上下文,即“m_list.GetWindowDC()”而不是“GetWindowDC()”。此外,要使用列表框的当前字体而不是默认系统字体来测量文本,您还需要“m_list.GetWindowDC()。SelectObject(m_list.GetFont())”。 – ulatekh 2013-10-22 00:17:07

试试这个:

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