using System;
using System.Windows.Forms;
using ;
using System.Drawing;namespace Mengxianhui.ComboBoxEx
{
class ComboBoxEx : ComboBox
{
private ImageList imageList;
public ImageList ImageList
{
get {return imageList;}
set {imageList = value;}
} public ComboBoxEx()
{
DrawMode = DrawMode.OwnerDrawFixed;
} protected override void OnDrawItem(DrawItemEventArgs ea)
{
ea.DrawBackground();
ea.DrawFocusRectangle(); ComboBoxExItem item;
Size imageSize = imageList.ImageSize;
Rectangle bounds = ea.Bounds; try
{
item = (ComboBoxExItem)Items[ea.Index]; if (item.ImageIndex != -1)
{
imageList.Draw(ea.Graphics, bounds.Left, ,
item.ImageIndex);
ea.Graphics.DrawString(item.Text, ea.Font, new
SolidBrush(ea.ForeColor), bounds.Left+imageSize.Width, );
}
else
{
ea.Graphics.DrawString(item.Text, ea.Font, new
SolidBrush(ea.ForeColor), bounds.Left, );
}
}
catch
{
if (ea.Index != -1)
{
ea.Graphics.DrawString(Items[ea.Index].ToString(), ea.Font, new
SolidBrush(ea.ForeColor), bounds.Left, );
}
else
{
ea.Graphics.DrawString(Text, ea.Font, new
SolidBrush(ea.ForeColor), bounds.Left, );
}
} base.OnDrawItem(ea);
}
} class ComboBoxExItem
{
private string _text;
public string Text
{
get {return _text;}
set {_text = value;}
} private int _imageIndex;
public int ImageIndex
{
get {return _imageIndex;}
set {_imageIndex = value;}
} public ComboBoxExItem()
: this("")
{
} public ComboBoxExItem(string text)
: this(text, -1)
{
} public ComboBoxExItem(string text, int imageIndex)
{
_text = text;
_imageIndex = imageIndex;
} public override string ToString()
{
return _text;
}
}}使用方法:
1.在form类里声明
public class Form1 : System.Windows.Forms.Form
{
private System.ComponentModel.IContainer components;
private ComboBoxEx comboBox2;2.初始化组件
private void InitializeComponent()
{
ComboBoxEx comboBox2 = new ComboBoxEx();
comboBox2.Width = 200; comboBox2.Items.Add(new ComboBoxExItem("【孟宪会之精彩世界】", 0));
comboBox2.Items.Add(new ComboBoxExItem("【孟宪会之精彩世界】", 1));
comboBox2.Items.Add(new ComboBoxExItem("【孟宪会之精彩世界】", 2));
this.Controls.AddRange(new System.Windows.Forms.Control[] {comboBox2});
ImageList imageList1 = new ImageList();
imageList1.Images.Add(Image.FromFile(@"D:\TEST\lib\db0.bmp"));
imageList1.Images.Add(Image.FromFile(@"D:\TEST\lib\db0.bmp"));
imageList1.Images.Add(Image.FromFile(@"D:\TEST\lib\db0.bmp"));
comboBox2.ImageList = imageList1;
this.SuspendLayout();
















