System.ArgumentException when drawing bitmaps in WPF from WinForms

We’ve been having this annoying crash going on for a while. We’ve seen it show up in Eqatec Analytics for a while, but since the stacktrace never had any of our code in it, we we’re a bit perplexed of what to do.

This is the stacktrace:

at System.Drawing.Bitmap..ctor(Int32 width, Int32 height, PixelFormat format)
  at System.Drawing.Bitmap..ctor(Int32 width, Int32 height)
  at System.Drawing.Icon.ToBitmap()
  at System.Windows.Forms.ThreadExceptionDialog..ctor(Exception t)
  at System.Windows.Forms.Application.ThreadContext.OnThreadException(Exception t)
  at System.Windows.Forms.Control.WndProcException(Exception e)
  at System.Windows.Forms.Control.ControlNativeWindow.OnThreadException(Exception e)
  at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
  at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
  at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
  at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
  at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
  at System.Windows.Forms.Application.Run(Form mainForm)

Then one day I got a report describing the crash and I said what the hell. So I started Googling for possible causes, could we find a service pack that solves the issue or just get an idea of whats going on.

When I stumble on a post claming that there was a GDI handle leak when converting bitmaps to imagesources, typically done when working with resources in a winforms applciation to support wpf.

The more I Googled the GDI leak the more apparent it became that this might be the root cause of our troubles. Luckly after some more research I found this article on Code Project describing our exact scenario and had itterated over the problem several times. If you run into this issue I highly recommend giving the article a read, and this post is primarily to help expose the article to others with similar issues.

Bitmap to BitmapSource at Code Project