Skip to content

Instantly share code, notes, and snippets.

@sachintha81
Created January 13, 2017 21:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sachintha81/c97ce63d2a827cbb38c3ed86331f11da to your computer and use it in GitHub Desktop.
Save sachintha81/c97ce63d2a827cbb38c3ed86331f11da to your computer and use it in GitHub Desktop.
WPF + C# Color Handling
namespace ColorLibrary
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private static String HexConverter(System.Drawing.Color c)
{
return ""#"" + c.R.ToString(""X2"") + c.G.ToString(""X2"") + c.B.ToString(""X2"");
}
public static List<System.Drawing.Color> ColorStructToList()
{
return typeof(System.Drawing.Color).GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public)
.Select(c => (System.Drawing.Color)c.GetValue(null, null))
.ToList();
}
private System.Drawing.Color GetSystemDrawingColorFromHexString(string hexString)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(hexString, @""[#]([0-9]|[a-f]|[A-F]){6}\b""))
throw new ArgumentException();
int red = int.Parse(hexString.Substring(1, 2), NumberStyles.HexNumber);
int green = int.Parse(hexString.Substring(3, 2), NumberStyles.HexNumber);
int blue = int.Parse(hexString.Substring(5, 2), NumberStyles.HexNumber);
return System.Drawing.Color.FromArgb(red, green, blue);
}
private string GetColor(string colorCode)
{
System.Drawing.Color color = GetSystemDrawingColorFromHexString(colorCode);
return color.Name;
}
}
}
@sachintha81
Copy link
Author

HexConverter()

Takes a System.Drawing.Color object and outputs the HTML code of the color.

ColorStructToList()

Creates a list of all the C# colors.

GetSystemDrawingColorFromHexString()

Converts a HTML color code into a System.Drawing.Color object.

GetColor()

Converts an HTML color code into a color name of a System.Drawing.Color object.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment