public static Color ConvertFromString(string strValue, CultureInfo culture) { string text = strValue.Trim(); if (text.Length == 0) { return(Color.Empty); } { Color c; // First, check to see if this is a standard name. // if (ColorTable.TryGetNamedColor(text, out c)) { return(c); } } if (culture == null) { culture = CultureInfo.CurrentCulture; } char sep = culture.TextInfo.ListSeparator[0]; // If the value is a 6 digit hex number only, then // we want to treat the Alpha as 255, not 0 // if (text.IndexOf(sep) == -1) { // text can be '' (empty quoted string) if (text.Length >= 2 && (text[0] == '\'' || text[0] == '"') && text[0] == text[text.Length - 1]) { // In quotes means a named value string colorName = text.Substring(1, text.Length - 2); return(Color.FromName(colorName)); } else if ((text.Length == 7 && text[0] == '#') || (text.Length == 8 && (text.StartsWith("0x") || text.StartsWith("0X"))) || (text.Length == 8 && (text.StartsWith("&h") || text.StartsWith("&H")))) { // Note: int.Parse will raise exception if value cannot be converted. return(PossibleKnownColor(Color.FromArgb(unchecked ((int)(0xFF000000 | (uint)IntFromString(text, culture)))))); } } // Nope. Parse the RGBA from the text. // string[] tokens = text.Split(sep); int[] values = new int[tokens.Length]; for (int i = 0; i < values.Length; i++) { values[i] = unchecked (IntFromString(tokens[i], culture)); } // We should now have a number of parsed integer values. // We support 1, 3, or 4 arguments: // // 1 -- full ARGB encoded // 3 -- RGB // 4 -- ARGB // switch (values.Length) { case 1: return(PossibleKnownColor(Color.FromArgb(values[0]))); case 3: return(PossibleKnownColor(Color.FromArgb(values[0], values[1], values[2]))); case 4: return(PossibleKnownColor(Color.FromArgb(values[0], values[1], values[2], values[3]))); } throw new ArgumentException($"InvalidColor: {text}"); }