C#listBox使用DrawItem来绘制Item,就算显示的内容(图片和字符串)都显示不下了,就出不了水平滚动条,哪位帮忙看一下:
this.listBox1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
……
}
private void listBox1_MeasureItem(object sender, MeasureItemEventArgs e)
{
e.ItemHeight = 20;
e.ItemWidth = 600;不知道为什么这个属性就是不起作用
}
this.listBox1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
……
}
private void listBox1_MeasureItem(object sender, MeasureItemEventArgs e)
{
e.ItemHeight = 20;
e.ItemWidth = 600;不知道为什么这个属性就是不起作用
}
this.listBox1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
是能够出水平滚动条的,只是在OwnerDrawVariable时,不显示不了水平滚动条
,不知道为什么!
发现将 HorizontalExtent 设置为比较大的取值以后(大于 ListBox.Width 就可以滚动了,但应该统计一下 ListBox 中最宽的 Item 的宽度)就可以了。
上述试验都在 VS 2005/.NET 2.0 下进行。
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);public void UpdateHScrllBar()
{
SendMessage(this.Handle, 0x194, maxLength, 0);
}
声明一个用来记录最大宽度的变量并初始化为0,比如:private int maxLength;protected override void OnMeasureItem(MeasureItemEventArgs e)
{
base.OnMeasureItem(e);
SizeF _size = e.Graphics.MeasureString(this.Items[e.Index].ToString(), this.Font); e.ItemWidth = (int)Math.Ceiling(_size.Width);
e.ItemHeight = (int)Math.Ceiling(_size.Height);
if (e.ItemWidth > this.maxLength)
{
this.maxLength = e.ItemWidth;
}
}protected override void OnDrawItem(DrawItemEventArgs e)
{
base.OnDrawItem(e);
e.DrawBackground();
e.DrawFocusRectangle();
using (SolidBrush brush = new SolidBrush(e.ForeColor))
{
Rectangle bound = e.Bounds;
e.Graphics.DrawString(this.Items[e.Index].ToString(), this.Font, brush, bound, null);
}
}添加对WndProc的处理:protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == 0x114)
{
this.Invalidate();
}
}
在每次对Items有改动的时候调用UpdateHScrllBar方法来更新滚动条的显示就可以了。试试看!
hbxtlhx 的方法我没试,应该也是可以的,
分数平分,谢谢两位!
listbox:
{MultiColumn =false,HorizontalExtent=true,水平+垂直}
{MultiColumn =true ,HorizontalExtent=true, 只水平}
{MultiColumn =true ,HorizontalExtent=false,只水平}
{MultiColumn =false,HorizontalExtent=false,只垂直 }通过这两个属性的设置,就可以做出滚动条的,,
this.logListBox.HorizontalExtent = Math.Max(this.logListBox.HorizontalExtent,(int)this.logListBox.CreateGraphics().MeasureString(info.Replace('\n','\r'), this.logListBox.Font).Width + 10);info是当前要添加的一行内容,info.Replace('\n','\r')的目的是替换掉字串中的回车符,因为MeasureString()好象只测量字串中第一个回车符之前的所有字符的size,因此若info是多行字串时,测量出来的结果就不对了