欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#构造ColorComboBox(颜色下拉框)

程序员文章站 2024-02-23 09:21:22
复制代码 代码如下:    class colorcombobox : combobox    { &...

复制代码 代码如下:

    class colorcombobox : combobox
    {
        /// <summary>
        /// 当前选中色
        /// </summary>
        public color selectedcolor
        {
            get { return color.fromname(this.text); }
        }
        /// <summary>
        /// 构造函数,构造颜色下拉列表
        /// </summary>
        public colorcombobox()
        {
            this.drawmode = drawmode.ownerdrawfixed;
            this.dropdownstyle = comboboxstyle.dropdownlist;
            this.itemheight = 25;

            propertyinfo[] propinfolist = typeof(color).getproperties(bindingflags.static | bindingflags.declaredonly | bindingflags.public);
            foreach (propertyinfo c in propinfolist)
            {
                this.items.add(c.name);
            }
            this.text = "black"; //设置默认色
        }

        protected override void ondrawitem(drawitemeventargs e)
        {
            rectangle rect = e.bounds;

            if (e.index >= 0)
            {
                string colorname = this.items[e.index].tostring();
                color c = color.fromname(colorname);
                using (brush b = new solidbrush(c)) //预留下拉项间距
                {
                    e.graphics.fillrectangle(b, rect.x, rect.y + 2, rect.width, rect.height - 4);
                }
            }
        }