c#新手笔记之颜色下拉框

来源:互联网 发布:工程预算软件破解版 编辑:程序博客网 时间:2024/05/17 22:25

颜色填充下拉框

代码:

using System.Reflection;

 
private void FillColorToCmb(ComboBox cmb)
        
{
            cmb.DrawMode 
= DrawMode.OwnerDrawFixed;
            cmb.DropDownStyle 
= ComboBoxStyle.DropDownList;
            cmb.DrawItem 
+=new DrawItemEventHandler(cmb_DrawItem);
            cmb.ItemHeight 
= 18;
            cmb.BeginUpdate();
            cmb.Items.Clear();           
            
foreach(PropertyInfo pi in typeof(Color).GetProperties(BindingFlags.Public|BindingFlags.Static))
            
{
                cmb.Items.Add(pi.Name);
            }

            cmb.EndUpdate();
        }


        
void  cmb_DrawItem(object sender, DrawItemEventArgs e)
        
{
            
if(e.Index<0)
                
return;
            e.DrawBackground();
            Rectangle rect 
= new Rectangle(4, e.Bounds.Top + 2, e.Bounds.Height+10, e.Bounds.Height - 4);         
            ComboBox cmb 
= (ComboBox)sender;
            
string colorName = cmb.Items[e.Index].ToString();
            SolidBrush b 
= new SolidBrush(Color.FromName(colorName));
            e.Graphics.FillRectangle(b, rect);
            e.Graphics.DrawRectangle(Pens.Black, rect);
            Font myFont 
= new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular);
            e.Graphics.DrawString(colorName, myFont, Brushes.Black,
                
new RectangleF(e.Bounds.X + rect.Width + 4, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height));
            e.DrawFocusRectangle();
        }