Convert System.Windows.Media.Pen to System.Drawing.Pen

Has anyone done a complete conversion from wpf Pen to gdi + one?

It doesn't seem complicated at first: use a constructor with the appropriate brush. But there are so many small details: different brushes (5 in wpf and 5 in gdi + with different names, properties, etc.), as well as the properties of the pen itself.

Perhaps there is a very simple solution, for example ToString() / Parse() alone or through serialization or perhaps a dedicated method or hidden class. Do not want to go in a long and wrong way if(type is ...) .

Here is one possible approach (may not work to demonstrate)

 using System.Windows.Media; using GDI = System.Drawing; public static GDI.Pen ToGDI(this Pen pen) { var brush = pen.Brush; var thickness = pen.Thickness; if(brush is SolidColorBrush) { var color = ((SolidColorBrush)brush).Color; return new GDI.Pen(new GDI.SolidBrush(Colors.FromArgb(color.A, color.R, color.G, color.B)), (float)thickness); } else if(brush is ...) { ... } } 
+7
c # winforms wpf
source share
1 answer

You cannot convert from a WPF pen to a GDI pen or vice versa, because these are two completely different systems for drawing in windows. The best you can do is create a new pen with properties as close as possible to the original pen.

The reason for this is that WPF does not use GDI to draw window contents (regardless of the WPF / GDI interaction conditions). Instead, WPF uses its own renderer based, if I'm not mistaken in Direct2D and Direct3D. Thus, a pen in WPF is not the same as in GDI, where it exists as an actual primitive graphic drawing object.

If you need GDI handles that are similar to existing WPF handles, you really have no choice but to write a bunch of if or switch managed codes to configure and return new System.Drawing.Pen. There is no other way.

+1
source share

All Articles