如何制作可以选择的颜色网格?

时间:2014-05-19 11:37:23

标签: c# winforms colors palette

如何使用可以选择的颜色制作一种网格,并将其保存到选择的字段中?就像Twitch中的聊天选项一样。

enter image description here

2 个答案:

答案 0 :(得分:2)

Windows窗体提供ColorDialog

ColorDialog colorDialog = new ColorDialog();
colorDialog.ShowDialog();

可以使用以下方式调用所选颜色:

colorDialog.Color

答案 1 :(得分:1)

您需要的只是TableLayoutPanel及其每个单元格的面板:

public partial class MainForm : Form
{
    private Color selected_color;
    private List<Color> colors;
    public MainForm()
    {
        InitializeComponent();
        colors = new List<Color>();
        colors.Add(Color.Red);
        colors.Add(Color.Green);
        colors.Add(Color.Blue);
        colors.Add(Color.Yellow);
        colors.Add(Color.Teal);
        colors.Add(Color.RosyBrown);
        colors.Add(Color.Lime);
        colors.Add(Color.Gray);
        tableLayoutPanel.CellBorderStyle = TableLayoutPanelCellBorderStyle.OutsetDouble;
        for (byte i = 0; i < tableLayoutPanel.Controls.Count; i++)
        {
            Panel p = tableLayoutPanel.Controls[i] as Panel;
            p.BackColor = colors[i];
            p.Click += panel_click;
        }
    }
    private void panel_click(object sender, EventArgs e)
    {
        Panel p = sender as Panel;
        selected_color = p.BackColor;
        lbl_color.Text = selected_color.ToString();
        lbl_color.ForeColor = selected_color;
    }
    private void btn_showMoreColours_Click(object sender, EventArgs e)
    {
        Panel[] panels = new Panel[4];
        for (byte i = 0; i < panels.Length; i++)
        {
            panels[i] = new Panel();
            panels[i].Dock = DockStyle.Fill;
            panels[i].Location = new System.Drawing.Point(3, 3);
            panels[i].Name = "panel" + (i + 4);
            panels[i].Size = new System.Drawing.Size(123, 100);
            panels[i].BackColor = colors[i + 4];
            panels[i].Click += panel_click;
            tableLayoutPanel.Controls.Add(panels[i]);
        }
        Size = new Size(Size.Width, Size.Height * 2);
    }
}

单击一个单元格后,您将获得选择颜色字段selected_color。 img

修改

A已添加显示更多颜色按钮。它将扩展如下所示: img3

img2

Source code here