在form上添加一個列表框控件.
public Form1()
{
InitializeComponent();
listBox1.DrawMode = DrawMode.OwnerDrawFixed; //控件中的每個列表項具有相同的大小
listBox1.ItemHeight = 20; //設置每個列表項的的高度
}
//列表框自繪觸發事件
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
//e.DrawBackground();
Graphics g = e.Graphics; // 獲取列表項的圖形對象
Font font = new Font("微軟雅黑", 15f); //設置列表框列表項的字體
Rectangle rect = new Rectangle(); //設置每個列表項所在矩形框的大小,這裏取默認的值
rect.X = e.Bounds.X;
rect.Y = e.Bounds.Y;
Brush textBrush;
//當列表項被單擊時,則高亮顯示
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{
g.FillRectangle( SystemBrushes.Highlight, rect);
textBrush = SystemBrushes.Highlight;
g.DrawRectangle(new Pen(Color.Red), e.Bounds);
}
else
{
g.FillRectangle( SystemBrushes.Window, rect);
textBrush = SystemBrushes.WindowText;
g.DrawRectangle(new Pen(e.BackColor), e.Bounds);
}
//繪製每個列表項
g.DrawString(
listBox1.Items[e.Index].ToString(), font, textBrush, rect, StringFormat.GenericDefault);
}
private void Form1_Load(object sender, EventArgs e)
{
listBox1.Items.AddRange(new Object[] { "Red Item", "Orange Item", "Purple Item" });
}