c# 颜色选择控件的实现代码

参考ColorComboBox做修改,并对颜色名做些修正,用于CR MVMixer产品中,聊作备忘~

效果图:

代码:

//颜色拾取框
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace CRMVMixer
{
    //event handler delegate
    public delegate void ColorChangedHandler(object sender, ColorChangeArgs e);

    [ToolboxBitmap(typeof(ComboBox))]
    public class ColorComboBox : ComboBox
    {
        private PopupWindow popupWnd;
        private ColorPopup colors = new ColorPopup();
        private Color selectedColor = Color.Black;
        private Timer timer = new Timer();
        public event ColorChangedHandler ColorChanged;

        //constructor...
        public ColorComboBox()
            : this(Color.Black)
        {
        }

        public ColorComboBox(Color selectedColor)
        {
            this.SuspendLayout();
            //
            // ColorCombo
            //
            this.AutoSize = false;
            this.Size = new Size(92, 22);
            this.Text = string.Empty;
            this.DrawMode = DrawMode.OwnerDrawFixed;
            this.DropDownStyle = ComboBoxStyle.DropDownList;
            this.ItemHeight = 16;

            timer.Tick += new EventHandler(OnCheckStatus);
            timer.Interval = 50;
            timer.Start();
            colors.SelectedColor = this.selectedColor = selectedColor;
            this.ResumeLayout(false);
        }

        [DefaultValue(typeof(Color), "Black")]
        public Color SelectedColor
        {
            get { return selectedColor; }
            set
            {
                selectedColor = value;
                colors.SelectedColor = value;
                Invalidate();
            }
        }

        protected override void WndProc(ref Message m)
        {
            //256: WM_KEYDOWN, 513: WM_LBUTTONDOWN, 515: WM_LBUTTONDBLCLK
            if (m.Msg == 256 || m.Msg == 513 || m.Msg == 515)
            {
                if (m.Msg == 513)
                    PopupColorPalette();
                return;
            }
            base.WndProc(ref   m);
        }

        private void PopupColorPalette()
        {
            //create a popup window
            popupWnd = new PopupWindow(colors);

            //calculate its position in screen coordinates
            Rectangle rect = Bounds;
            rect = this.Parent.RectangleToScreen(rect);
            Point pt = new Point(rect.Left, rect.Bottom);

            //tell it that we want the ColorChanged event
            popupWnd.ColorChanged += new ColorChangedHandler(OnColorChanged);

            //show the popup
            popupWnd.Show(pt);
            //disable the button so that the user can't click it
            //while the popup is being displayed
            this.Enabled = false;
            this.timer.Start();
        }

        //event handler for the color change event from the popup window
        //simply relay the event to the parent control
        protected void OnColorChanged(object sender, ColorChangeArgs e)
        {
            //if a someone wants the event, and the color has actually changed
            //call the event handler
            if (ColorChanged != null && e.color != this.selectedColor)
            {
                this.selectedColor = e.color;
                ColorChanged(this, e);
            }
            else //otherwise simply make note of the new color
                this.selectedColor = e.color;
        }

        protected override void OnDrawItem(DrawItemEventArgs e)
        {
            var g = e.Graphics;
            e.DrawBackground();
            var brush = new SolidBrush(this.selectedColor);
            var rect = e.Bounds;
            rect.Width -= 1;
            rect.Height -= 1;
            g.FillRectangle(brush, rect);
            g.DrawRectangle(Pens.Black, rect);
            e.DrawFocusRectangle();
        }

        //This is the timer call back function. It checks to see
        //if the popup went from a visible state to an close state
        //if so then it will uncheck and enable the button
        private void OnCheckStatus(object sender, EventArgs e)
        {
            if (popupWnd != null && !popupWnd.Visible)
            {
                this.timer.Stop();
                this.Enabled = true;
            }
        }

        /// <summary>
        /// a button style radio button that shows a color
        /// </summary>
        private class ColorRadioButton : RadioButton
        {
            public ColorRadioButton(Color color, Color backColor)
            {
                this.ClientSize = new Size(21, 21);
                this.Appearance = Appearance.Button;
                this.Name = "button";
                this.Visible = true;
                this.ForeColor = color;
                this.FlatAppearance.BorderColor = backColor;
                this.FlatAppearance.BorderSize = 0;
                this.FlatStyle = FlatStyle.Flat;
                this.Paint += new PaintEventHandler(OnPaintButton);
            }

            private void OnPaintButton(object sender, PaintEventArgs e)
            {
                //paint a square on the face of the button using the controls foreground color
                Rectangle colorRect = new Rectangle(ClientRectangle.Left + 5, ClientRectangle.Top + 5, ClientRectangle.Width - 9, ClientRectangle.Height - 9);
                e.Graphics.FillRectangle(new SolidBrush(this.ForeColor), colorRect);
                e.Graphics.DrawRectangle(Pens.DarkGray, colorRect);
            }
        }

        ///<summary>
        ///this is the popup window.  This window will be the parent of the
        ///window with the color controls on it
        ///</summary>
        private class PopupWindow : ToolStripDropDown
        {
            public event ColorChangedHandler ColorChanged;
            private ToolStripControlHost host;
            private ColorPopup content;

            public Color SelectedColor
            {
                get { return content.SelectedColor; }
            }

            public PopupWindow(ColorPopup content)
            {
                if (content == null)
                    throw new ArgumentNullException("content");

                this.content = content;
                this.AutoSize = false;
                this.DoubleBuffered = true;
                this.ResizeRedraw = true;
                //create a host that will host the content
                host = new ToolStripControlHost(content);

                this.Padding = Margin = host.Padding = host.Margin = Padding.Empty;
                this.MinimumSize = content.MinimumSize;
                content.MinimumSize = content.Size;
                MaximumSize = new Size(content.Size.Width + 1, content.Size.Height + 1);
                content.MaximumSize = new Size(content.Size.Width + 1, content.Size.Height + 1);
                Size = new Size(content.Size.Width + 1, content.Size.Height + 1);

                content.Location = Point.Empty;
                //add the host to the list
                Items.Add(host);
            }

            protected override void OnClosed(ToolStripDropDownClosedEventArgs e)
            {
                //when the window close tell the parent that the color changed
                if (ColorChanged != null)
                    ColorChanged(this, new ColorChangeArgs(this.SelectedColor));
            }
        }

        ///<summary>
        ///this class represends the control that has all the color radio buttons.
        ///this control gets embedded into the PopupWindow class.
        ///</summary>
        private class ColorPopup : UserControl
        {
            //private Color[] colors = { Color.Black, Color.Gray, Color.Maroon, Color.Olive, Color.Green, Color.Teal, Color.Navy, Color.Purple, Color.White, Color.Silver, Color.Red, Color.Yellow, Color.Lime, Color.Aqua, Color.Blue, Color.Fuchsia };
            private Color[] colors = {
                Color.Black, Color.Navy, Color.DarkGreen, Color.DarkCyan, Color.DarkRed, Color.DarkMagenta, Color.Olive,
                Color.LightGray, Color.DarkGray, Color.Blue, Color.Lime, Color.Cyan, Color.Red, Color.Fuchsia,
                Color.Yellow, Color.White, Color.RoyalBlue, Color.MediumBlue,  Color.LightGreen, Color.MediumSpringGreen, Color.Chocolate,
                Color.Pink, Color.Khaki, Color.WhiteSmoke, Color.BlueViolet, Color.DeepSkyBlue, Color.OliveDrab, Color.SteelBlue,
                Color.DarkOrange, Color.Tomato, Color.HotPink, Color.DimGray,
            };
            private string[] colorNames = {
                "黑色", "藏青", "深绿", "深青", "红褐", "洋红", "褐绿",
                "浅灰", "灰色", "蓝色", "绿色", "青色", "红色", "紫红",
                "黄色", "白色", "蓝灰", "藏蓝", "淡绿", "青绿", "黄褐",
                "粉红", "嫩黄", "银白", "紫色", "天蓝", "灰绿", "青蓝",
                "橙黄", "桃红", "英红", "深灰"
            };
            private ToolTip toolTip = new ToolTip();
            private ColorRadioButton[] buttons;
            private Button moreColorsBtn;
            private Color selectedColor = Color.Black;

            ///<summary>
            ///get or set the selected color
            ///</summary>
            public Color SelectedColor
            {
                get { return selectedColor; }
                set
                {
                    selectedColor = value;
                    Color[] colors = this.colors;
                    for (int i = 0; i < colors.Length; i++)
                        buttons[i].Checked = selectedColor == colors[i];
                }
            }

            private void InitializeComponent()
            {
                this.SuspendLayout();
                this.Name = "Color Popup";
                this.Text = string.Empty;
                this.ResumeLayout(false);
            }

            public ColorPopup()
            {
                InitializeComponent();

                SetupButtons();
                this.Paint += new PaintEventHandler(OnPaintBorder);
            }

            //place the buttons on the window.
            private void SetupButtons()
            {
                Controls.Clear();

                int x = 1;
                int y = 2;
                int breakCount = 7;
                Color[] colors = this.colors;
                this.buttons = new ColorRadioButton[colors.Length];
                this.ClientSize = new Size(139, 137);
                //color buttons
                for (int i = 0; i < colors.Length; i++)
                {
                    if (i > 0 && i % breakCount == 0)
                    {
                        y += 19;
                        x = 1;
                    }
                    buttons[i] = new ColorRadioButton(colors[i], this.BackColor);
                    buttons[i].Location = new Point(x, y);
                    toolTip.SetToolTip(buttons[i], colorNames[i]);
                    Controls.Add(buttons[i]);
                    buttons[i].Click += new EventHandler(BtnClicked);
                    if (selectedColor == colors[i])
                        buttons[i].Checked = true;
                    x += 19;
                }

                //line...
                y += 24;
                var label = new Label();
                label.AutoSize = false;
                label.Text = string.Empty;
                label.Width = this.Width - 5;
                label.Height = 2;
                label.BorderStyle = BorderStyle.Fixed3D;
                label.Location = new Point(4, y);
                Controls.Add(label);

                //button
                y += 7;
                moreColorsBtn = new Button();
                moreColorsBtn.FlatStyle = FlatStyle.Popup;
                moreColorsBtn.Text = "其它颜色...";
                moreColorsBtn.Location = new Point(6, y);
                moreColorsBtn.ClientSize = new Size(127, 23);
                moreColorsBtn.Click += new EventHandler(OnMoreClicked);
                Controls.Add(moreColorsBtn);
            }

            private void OnPaintBorder(object sender, PaintEventArgs e)
            {
                var rect = this.ClientRectangle;
                rect.Width -= 1;
                rect.Height -= 1;
                e.Graphics.DrawRectangle(new Pen(SystemColors.WindowFrame), rect);
            }

            public void BtnClicked(object sender, EventArgs e)
            {
                selectedColor = ((ColorRadioButton)sender).ForeColor;
                ((ToolStripDropDown)Parent).Close();
            }

            public void OnMoreClicked(object sender, EventArgs e)
            {
                ColorDialog dlg = new ColorDialog();
                dlg.Color = SelectedColor;
                if (dlg.ShowDialog(this) == DialogResult.OK)
                    selectedColor = dlg.Color;
                ((ToolStripDropDown)Parent).Close();
            }
        }
    }

    //define the color changed event argument
    public class ColorChangeArgs : System.EventArgs
    {
        //the selected color
        public Color color;
        public ColorChangeArgs(Color color)
        {
            this.color = color;
        }
    }
}

以上就是c# 颜色选择控件的实现代码的详细内容,更多关于c# 颜色选择控件的资料请关注我们其它相关文章!

(0)

相关推荐

  • C#更改tabControl选项卡颜色的方法

    本文实例讲述了C#更改tabControl选项卡颜色的方法.分享给大家供大家参考,具体如下: private void Form1_Load(object sender, EventArgs e) { this.tabControl1.DrawMode = System.Windows.Forms.TabDrawMode.OwnerDrawFixed; this.tabControl1.DrawItem += new DrawItemEventHandler(this.tabControl1_D

  • C# 根据表格偶数、奇数加载不同颜色

    效果图: //偶数随机 Random evenRanm = new Random(); //奇数随机 Random oddRanm = new Random(); string[] listColor = new string[] { "#2BB669","#FF5750","#39AFEA","#9A0089", "#00CC6A","#717FF9","#4A5459&qu

  • C# 如何设置label(标签)控件的背景颜色为透明

    有时候,我们需要将控件的背景颜色设定为透明,比如说label(标签)控件.那么,如何将控件的背景颜色设定为透明?是不是只要将控件的BackColor属性设为Transparent(透明)就可以了呢?答案是否定的.看似很简单,其实不然,在实际操作过程中,很让人抓狂,抓狂到让你怀疑人生. 关于透明 首先要解释一下,什么叫做透明.在C#这里,透明就是指透过控件的背景,可以看到其父控件(容器)表面的颜色.所谓的透明,其实就是将父控件表面的颜色设定为自己的背景颜色. 设置控件背景颜色为透明的步骤和注意事项

  • C# 实现颜色渐变窗体控件详细讲解

    1.建议设置窗体为双缓冲绘图,可有效避免界面刷时引起的闪烁 this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); 2.代码实现 private Color Color1 = Color.Gray; //起始颜色 private Color Color2 = Color.White ; //目标颜色 private float changeAngle = 0f;

  • C#及WPF获取本机所有字体和颜色的方法

    本文实例讲述了C#及WPF获取本机所有字体和颜色的方法.分享给大家供大家参考.具体如下: WPF 获取所有的字体: System.Drawing.Text.InstalledFontCollection font = new System.Drawing.Text.InstalledFontCollection(); System.Drawing.FontFamily[] array= font.Families; foreach (var v in array) { MessageBox.Sh

  • C# 实现颜色的梯度渐变案例

    为了表示不同的浓度值,对颜色条应用颜色梯度变化,基本方法是对ARGB分量乘以一个渐变系数. 下面是对十种颜色应用的三个梯度值的过程. public void DrawRect(gasConcentration[] data) { Graphics graphic = pictureBox1.CreateGraphics(); Graphics graphic2 = pictureBox2.CreateGraphics(); int iCall2 = pictureBox2.Width/10; d

  • C#实现更改MDI窗体背景颜色的方法

    本文实例讲述了C#实现更改MDI窗体背景颜色的方法.分享给大家供大家参考.具体实现方法如下: /// <summary> /// 设置MDI背景 /// </summary> void RemoveMdiBackColor() { foreach (Control c in this.Controls) { if (c is MdiClient) { c.BackColor = this.BackColor; //颜色 c.BackgroundImage = this.Backgr

  • C# Color.FromArgb()及系统颜色对照表一览

    C#关于颜色值的表示: 常用的颜色值表示方式有两种,一种是10进制的RGB值表示,如(0,113,255),三个值分别表示(红,绿,蓝):一种是16进制的颜色码表示,如#ff3212.这两种形式在编程中都可以用到.若是在VS设计器中,设置某个控件的前景色或背景色时,可直接用0,113,255或#ff3212的形式,而在后台代码中,也可以通过Color.FromArgb()方法使用这两种形式来定义颜色. Color.FromArgb()方法的重载及使用 Color.FromArgb()方法共有四种

  • C#利用Label标签控件模拟窗体标题的移动及窗体颜色不断变换效果

    前言 标签(Label)控件是最常用的控件,在任何Windows应用程序中都可以中都可以看到标签控件.标签控件用于显示用户不能编辑的文件或图像,常用于对窗体上各种控件进行标注或说明. 在窗体中添加标签控件时,会创建一个Label类的实例.Label控件派生自Control控件,和其他控件一样支持事件,但通常不需要添加任何事件代码. 本文主要给大家介绍了关于C#用Label标签控件模拟窗体标题移动及窗体颜色不断变换的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧. 开发工

  • C#使用RichTextBox实现替换文字及改变字体颜色功能示例

    本文实例讲述了C#使用RichTextBox实现替换文字及改变字体颜色功能.分享给大家供大家参考,具体如下: 替换文字 private void GenerateEntity() { try { string result = ChangeWords("specific content..."); txtContent.Text = result; ChangeColor(); } catch (Exception ex) { MessageBox.Show("类生成失败!错

随机推荐