none
Converting from Microsoft.Office.Interop.Word.WdColor to System.Windows.Media.Color

    General discussion

  • In my VSTO application, I was struggling to convert from WdColor enum to the Color struct. WdColor uses 24-bit integers but they are not RGB.

    As it turns out, WdColor seems to use BGR (the bytes are "backwards").

    There are surely better mathematical ways of accomplishing this, but for what it's worth here's my solution:

     

     public class WdColorColorConverter : IValueConverter
     {
      public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
    
       if (!(value is WdColor))
       {
        return Colors.Black;
       }
       else if ((WdColor)value == WdColor.wdColorAutomatic)
       {
        return Colors.Black;
       }
       else
       {
    
        int intValue = ((WdColor)value).GetHashCode();
        string hexValue = intValue.ToString("X").PadLeft(6, '0');
    
        string redHex = hexValue.Substring(4, 2);
        string greenHex = hexValue.Substring(2, 2);
        string blueHex = hexValue.Substring(0, 2);
    
        byte redByte = byte.Parse(redHex, System.Globalization.NumberStyles.AllowHexSpecifier);
        byte greenByte = byte.Parse(greenHex, System.Globalization.NumberStyles.AllowHexSpecifier);
        byte blueByte = byte.Parse(blueHex, System.Globalization.NumberStyles.AllowHexSpecifier);
    
        Color c = Color.FromRgb(redByte, greenByte, blueByte);
        return c;
    
       }
      }
    
    
    
      public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
       throw new NotImplementedException();
      }
     }
    
    It only converts from WdColor enum to Wpf's Color struct but ConvertBack would work the same way in reverse (changing an RGB color to BGR).
    • Changed type Sanctus Tuesday, September 21, 2010 6:28 PM
    Tuesday, September 21, 2010 6:27 PM