C# tip: converting color values between WPF and WinForms applications
Posted: (EET/GMT+2)
I'm currently working on a WPF application that hosts some older WinForms controls for hardware integrations. If you've worked with color codes in both applications, you know that in WPF applications, colors are specified using the Color class, which lives in the namespace System.Windows.Media.
On the other hand, in WinForms (Windows Forms) applications, you have a similarly named class Color, but this time from the namespace is System.Drawing.
In my application, I had the need to take a Color object in WPF, and specify the same color for a WinForms component. The problem is, you cannot directly assign a WPF Color object to a WinForms Color object, because they are different.
Luckily, you can pretty easily convert between both by using the RGB values, or if you want to have the alpha (transparency) channel too, ARGB values. Here's a quick example:
using System.Windows.Media;
using System.Drawing;
private void ConvertColors()
{
// convert a WPF color object to a WinForms color object
System.Windows.Media.Color wpfColor =
System.Windows.Media.Colors.Blue;
byte alpha = wpfColor.A;
byte red = wpfColor.R;
byte green = wpfColor.G;
byte blue = wpfColor.B;
System.Drawing.Color winFormsColor =
System.Drawing.Color.FromArgb(alpha, red, green, blue);
// convert a WinForms color object to a WPF color object
winFormsColor = System.Drawing.Color.Green;
alpha = winFormsColor.A;
red = winFormsColor.R;
green = winFormsColor.G;
blue = winFormsColor.B;
wpfColor = System.Windows.Media.Color.FromArgb(
alpha, red, green, blue);
}
You could also use a 32-bit integer value to do the conversion a bit more efficiently, but I believe the above method is more self-documenting.
Hope this helps!