Sunday, April 13, 2008

To OLE / From OLE color translator in WPF

In GDI+ (Winforms) world, there was very handy class inside System.Drawing. It named ColorTranslator and it used to translate from OLE integer color value into GDI+ Color and vice verse. In WPF there is no such class, so if you’re working with old COM/COM+ application you have either reference System.Drawing.dll or write those two methods yourself. I prefer to write it :)

public static class ColorTranslator
    {
        const int RedShift = 0;
        const int GreenShift = 8;
        const int BlueShift = 16;
        /// <summary>
        /// Translates an Ole color value to a System.Media.Color for WPF usage
        /// </summary>
        /// <param name="oleColor">Ole int32 color value</param>
        /// <returns>System.Media.Color color value</returns>
        public static Color FromOle(this int oleColor)
        {
            return Color.FromRgb(
                (byte)((oleColor >> RedShift) & 0xFF),
                (byte)((oleColor >> GreenShift) & 0xFF),
                (byte)((oleColor >> BlueShift) & 0xFF)
                );
        }

        /// <summary>
        /// Translates the specified System.Media.Color to an Ole color.
        /// </summary>
        /// <param name="wpfColor">System.Media.Color source value</param>
        /// <returns>Ole int32 color value</returns>
        public static int ToOle(Color wpfColor)
        {
            return wpfColor.R << RedShift | wpfColor.G << GreenShift | wpfColor.B << BlueShift;
        }
    }

Have a nice day and be good people.

No comments: