
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication17 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } /// <summary> /// 在这个函数之前必须修改listbox的DrawMode属性为OwnerDrawVariable /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void listBox1_DrawItem(object sender, DrawItemEventArgs e) { int index = e.Index;//获取当前要进行绘制的行的序号,从0开始。 Graphics g = e.Graphics;//获取Graphics对象。 Rectangle bound = e.Bounds;//获取当前要绘制的行的一个矩形范围。 string text = listBox1.Items[index].ToString();//获取当前要绘制的行的显示文本。 if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) { //如果当前行为选中行。 //绘制选中时要显示的蓝色边框。 g.DrawRectangle(Pens.Black, bound.Left, bound.Top, bound.Width - 1, bound.Height - 1); Rectangle rect = new Rectangle(bound.Left, bound.Top, bound.Width, bound.Height); //绘制选中时要显示的蓝色背景。 g.FillRectangle(Brushes.Red, rect); //绘制显示文本。 TextRenderer.DrawText(g, text, this.Font, rect, Color.Black, TextFormatFlags.VerticalCenter | TextFormatFlags.Left); } else { Rectangle rect = new Rectangle(bound.Left, (bound.Top ), bound.Width, bound.Height); if (index == 0) { g.FillRectangle(Brushes.Yellow, rect); } else if (index == 1) { g.FillRectangle(Brushes.YellowGreen, rect); } else { g.FillRectangle(Brushes.SkyBlue, rect); } TextRenderer.DrawText(g, text, this.Font, rect, Color.Black, TextFormatFlags.VerticalCenter | TextFormatFlags.Left); } } } }