定义:
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.ImageList imageList1;
private System.Windows.Forms.ImageList imageList1;
注意事项:
comboBox1下面两个属性一定要设为下面的值。
DrawMode:OwnerDrawFixed;
DropDownStyle:DropDownList;
DropDownStyle:DropDownList;
imageList1中一定要包函与所添加的项相同数目的图
关键方法:
此方法为comboBox1的DrawItem事件所引起的方法。
private void comboBox1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
{
Graphics g = e.Graphics ;
Rectangle r = e.Bounds ;
Size imageSize = imageList1.ImageSize;
Font fn = null ;
if ( e.Index >= 0 )
{
fn = (Font)fontArray[0];
string s = (string)comboBox1.Items[e.Index];
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Near;
if ( e.State == ( DrawItemState.NoAccelerator | DrawItemState.NoFocusRect))
{
//画条目背景
e.Graphics.FillRectangle(new SolidBrush(Color.Red) , r);
//绘制图像
imageList1.Draw(e.Graphics, r.Left, r.Top,e.Index);
//显示字符串
e.Graphics.DrawString( s , fn , new SolidBrush(Color.Black), r.Left+imageSize.Width ,r.Top);
//显示取得焦点时的虚线框
e.DrawFocusRectangle();
}
else
{
e.Graphics.FillRectangle(new SolidBrush(Color.LightBlue) , r);
imageList1.Draw(e.Graphics, r.Left, r.Top,e.Index);
e.Graphics.DrawString( s , fn , new SolidBrush(Color.Black),r.Left+imageSize.Width ,r.Top);
e.DrawFocusRectangle();
}
}
{
Graphics g = e.Graphics ;
Rectangle r = e.Bounds ;
Size imageSize = imageList1.ImageSize;
Font fn = null ;
if ( e.Index >= 0 )
{
fn = (Font)fontArray[0];
string s = (string)comboBox1.Items[e.Index];
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Near;
if ( e.State == ( DrawItemState.NoAccelerator | DrawItemState.NoFocusRect))
{
//画条目背景
e.Graphics.FillRectangle(new SolidBrush(Color.Red) , r);
//绘制图像
imageList1.Draw(e.Graphics, r.Left, r.Top,e.Index);
//显示字符串
e.Graphics.DrawString( s , fn , new SolidBrush(Color.Black), r.Left+imageSize.Width ,r.Top);
//显示取得焦点时的虚线框
e.DrawFocusRectangle();
}
else
{
e.Graphics.FillRectangle(new SolidBrush(Color.LightBlue) , r);
imageList1.Draw(e.Graphics, r.Left, r.Top,e.Index);
e.Graphics.DrawString( s , fn , new SolidBrush(Color.Black),r.Left+imageSize.Width ,r.Top);
e.DrawFocusRectangle();
}
}
}
comboBox1.Items.Add("小车");
comboBox1.Items.Add("视频");
comboBox1.Items.Add("信号灯");
comboBox1.Items.Add("视频");
comboBox1.Items.Add("信号灯");