Created
January 13, 2017 21:32
-
-
Save sachintha81/c97ce63d2a827cbb38c3ed86331f11da to your computer and use it in GitHub Desktop.
WPF + C# Color Handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.