调用Combobox的DrawItem和MeasureItem事件设置项字体的颜色和大小以及项的高度和宽度

 1 //窗体上添加一个名为comboBox2的combobox
 2private void Form1_Load(object sender, EventArgs e)
 3{
 4            this.comboBox2.DrawMode = DrawMode.OwnerDrawFixed;
 5            this.comboBox2.DataSource = new String[] "One""Two""Three" };
 6
 7            this.comboBox2.MeasureItem+=new MeasureItemEventHandler(comboBox2_MeasureItem);
 8            this.comboBox2.DrawItem += new DrawItemEventHandler(comboBox2_DrawItem);
 9}

10
11
12
13/// <summary>
14/// 设置文字底框的高度和宽度
15/// </summary>

16private void comboBox2_MeasureItem(object sender, MeasureItemEventArgs e)
17{
18
19           //根据项的索引设置底框高度
20            switch (e.Index)
21            {
22                case 0:
23                    e.ItemHeight = 15;
24                    break;
25                case 1:
26                    e.ItemHeight = 20;
27                    break;
28                case 2:
29                    e.ItemHeight = 25;
30                    break;
31            }

32            e.ItemWidth = 20;//设置项的宽度
33}

34
35/// <summary>
36/// 设置文字的颜色,也可以设置大小
37/// </summary>
38/// <param name="sender"></param>
39/// <param name="e"></param>

40private void comboBox2_DrawItem(object sender, DrawItemEventArgs e)
41 {
42            Brush myBrush = Brushes.Black;
43
44            e.DrawBackground();
45
46
47            //根据项的索引设置字体颜色
48            switch (e.Index)
49            {
50                case 0:
51                    myBrush = Brushes.Gray;
52                    break;
53                case 1:
54                    myBrush = Brushes.LawnGreen;
55                    break;
56                case 2:
57                    myBrush = Brushes.Tan;
58                    break;
59            }

60
61            //如果要设置大小则定义一个新的Font,用于替换e.Font
62            e.Graphics.DrawString(this.comboBox2.Items[e.Index].ToString(), e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
63            e.DrawFocusRectangle();
64}

65

 

该代码从MSDN摘取,但经过简化和测试!

posted @ 2008-09-27 17:44    阅读(5616)  评论(2编辑  收藏  举报