Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting CustomColors in a ColorDialog

Tags:

c#

colordialog

Custom color set in the color dialog are supposed to be set to {Blue, Blue} using the following code:

colorDialog1.CustomColors = new int[] { System.Drawing.Color.Blue.ToArgb(), 0xFF0000 };
colorDialog1.ShowDialog();

But, I am getting a different set {Black, Blue}:

enter image description here

Any idea What I am doing wrong here? Thanks.

like image 216
Afshin Avatar asked Jul 18 '12 17:07

Afshin


2 Answers

You need to use OLE colors. The simplist way to achieve this is using the built in ColorTranslator object, e.g.

colorDialog1.CustomColors = new int[] { 
                                        ColorTranslator.ToOle(Color.Blue), 
                                        ColorTranslator.ToOle(Color.Red)
                                      };
colorDialog1.ShowDialog(); 

If you need to convert from HTML colors, you can also use the ColorTranslator.FromHtml method, e.g.

colorDialog1.CustomColors = new int[]
                                {
                                    ColorTranslator.ToOle(Color.Blue), 
                                    ColorTranslator.ToOle(ColorTranslator.FromHtml("#FF0000"))
                                };
like image 122
George Johnston Avatar answered Nov 13 '22 16:11

George Johnston


If you have an array of colors, you can translate them using Linq:

colorDialog1.CustomColors = ThemeColors.Select(x => ColorTranslator.ToOle(x)).ToArray()

The ThemeColors array would be something like this:

public static Color[] ThemeColors
{
   get => new[]
   {
      Color.FromArgb(255, 185, 0),
      Color.FromArgb(231, 72, 86),
      Color.FromArgb(0, 120, 215),
      Color.FromArgb(0, 153, 188),
      Color.DarkOrange
   }
}

Note: Don't forget to add:

using System.Linq;
like image 28
Peyman M. Avatar answered Nov 13 '22 15:11

Peyman M.