tags:

views:

36

answers:

1

Is there a simple way to convert a System.Drawing.Pen into its unmanaged counterpart? Like, if you had a Pen like this:

Pen p = new Pen(Color.Blue, 1f);
IntPtr ptr = p.ToPtr();

I know this code doesn't work, but is there a way to do it similarly?

+1  A: 

The Penclass has an internal property NativePen which contains exactly what you want. You can access this property through reflection (if your code has the appropriate permissions) using:

Pen p = new Pen(Color.Blue, 1f);
PropertyInfo pi = typeof(Pen).GetProperty("NativePen", BindingFlags.Instance | BindingFlags.NonPublic);
IntPtr ip = (IntPtr)pi.GetValue(p, null);

Be aware that theoretically this might not work in future versions of the .NET-Framework, since internal properties could change ...

MartinStettner
Also notice that this won’t work with other .NET implementations (notably, Mono).
Konrad Rudolph
Well, I solved my problem without it, but this would probably have worked for my problem, so I'll mark it. Thanks anyway!
Bevin
@Konrad: Right. But I'm not sure if converting a Pen into an IntPtr would even make sense in mono. After all the conversion means accessing the underlying graphics system which can vary widly if you're on mono ...
MartinStettner
@Martin: true. My comment was actually meant as just that, not as a criticism. Your answer is still interesting (I *thought* I had upvoted it before).
Konrad Rudolph