C# WinForms 顏色選擇器教學,儲存自訂顏色

顏色選擇器

  
var colorDialog = new ColorDialog();
if (colorDialog.ShowDialog() == DialogResult.OK)
{
  Color color = colorDialog.Color;
}
    


儲存自訂顏色

在顏色選擇視窗的下方有 8x2 的格子,可以自訂顏色,但是關閉程式後再次啟動時下面的顏色就會不見了,有沒有辦法儲存呢?
這 16 個格子的顏色是儲存在 colorDialog.CustomColors 裡面,只要把這些顏色記錄下來就可以了

最簡單的方式如下:
  
var file = "color.txt";

// 讀取顏色
if (File.Exists(file))
{
    colorDialog.CustomColors = File.ReadAllText(file).Split(',').Select(int.Parse).ToArray();;
}
// 儲存顏色
if (colorDialog.ShowDialog() == DialogResult.OK)
{
    button.BackColor = colorDialog.Color;
    File.WriteAllText(file, string.Join(",", colorDialog.CustomColors));
}
    

完整範例程式碼

  

        var colorDialog = new ColorDialog();
        var file = "color.txt";

        // 讀取顏色
        if (File.Exists(file))
        {
            colorDialog.CustomColors = File.ReadAllText(file).Split(',').Select(int.Parse).ToArray();;
        }


        Button button = new Button();
        button.Text = "color";
        button.Size = new Size(100, 30);
        button.Location = new Point(100, 100);
        this.Controls.Add(button);
        button.Click += (sender, e) =>
        {
            if (colorDialog.ShowDialog() == DialogResult.OK)
            {
                button.BackColor = colorDialog.Color;
                File.WriteAllText(file, string.Join(",", colorDialog.CustomColors)); // 儲存顏色
            }
        };
    

留言