要实现这个效果很简单,只需自定义一个类继承ListBox,然后重写OnDrawItem事件就可以了,下面看代码
class CListbox:ListBox
{
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern IntPtr GetWindowDC(IntPtr hWnd);
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
protected override void OnDrawItem(DrawItemEventArgs e)
{
Graphics g = e.Graphics;
if (e.Index % 2 == 0)
{
g.FillRectangle(new SolidBrush(Color.WhiteSmoke), e.Bounds);
g.DrawString(Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Blue), e.Bounds);
}
else
{
g.FillRectangle(new SolidBrush(Color.WhiteSmoke), e.Bounds);
g.DrawString(Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Red), e.Bounds);
}
e.DrawFocusRectangle();
g.Dispose();
base.OnDrawItem(e);
}
//捕获消息,画listbox边框
protected override void WndProc(ref Message m)
{
if (m.Msg == 0xf || m.Msg == 0x133)
{
IntPtr hDC = GetWindowDC(m.HWnd);
System.Drawing.Pen pen = new Pen(Color.YellowGreen, 1);
System.Drawing.Graphics g = Graphics.FromHdc(hDC);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
g.DrawRectangle(pen, 0, 0, this.Width - 1, this.Height - 1);
pen.Dispose();
g.Dispose();
ReleaseDC(m.HWnd, hDC);
}
base.WndProc(ref m);
}
}
应用如下:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private CListbox mylistbox;
private void Form1_Load(object sender, EventArgs e)
{
mylistbox = new CListbox();
mylistbox.ItemHeight = 32;
mylistbox.DrawMode = DrawMode.OwnerDrawVariable;
mylistbox.Height = 150;
mylistbox.Width = 250;
mylistbox.Items.Add("第一行显示!");
mylistbox.Items.Add("第二行显示!");
mylistbox.Items.Add("第三行显示!");
mylistbox.Items.Add("第四行显示!");
mylistbox.Items.Add("第五行显示!");
mylistbox.Items.Add("第六行显示!");
mylistbox.Items.Add("第七行显示!");
mylistbox.Items.Add("第八行显示!");
mylistbox.Items.Add("第九行显示!");
mylistbox.Items.Add("第十行显示!");
mylistbox.Items.Add("第十一行显示!");
mylistbox.Items.Add("第十二行显示!");
this.Controls.Add(mylistbox);
}
}
效果如下: