Sunday, May 06, 2007

How to use System.Drawing.Bitmap (HBitmap) in WPF

Actually, the question is: "How to use nice feature of Resource code generation, presented in VS2005 within WPF". Well, that's not really efficient way, but whatever. As you, probably, know in WinForms (.NET2.0) and Visual Studio 2005 there is code generator for system resources. It makes us able to have intellisense support of VS development environment for loading resources from the application.

Actually, the code generator creates a butch of static properties, that gets objects from application ResourceManager. If you'll take a look into Reesources.Designer.cs file, you'll find there internal static readonly properties like this

internal static System.Drawing.Bitmap p1060981 {
get {
object obj = ResourceManager.GetObject("p1060981", resourceCulture);
return ((System.Drawing.Bitmap)(obj));


How to get this and load my images (or any other resources) and use then in WPF this way?

image.Source = ResourceHelper1.Properties.Resources.p1060981;


Well, you can not and the main reason is, that it returns System.Drawing.Bitmap, which actually, HBitmap and can not be used directly as image source for WPF. But if you really want try this small helper

public static BitmapSource loadBitmap(System.Drawing.Bitmap source)
return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(source.GetHbitmap(),IntPtr.Zero,Int32Rect.Empty,


It gets System.Drawing.Bitmap (from WindowsBased) and converts it into BitmapSource, which can be actually used as image source for your Image control in WPF.

This is not very efficient way. It's much better to use Resources management of WPF as described here, but in some cases (this one is not reason :) ) you have to use Forms ResourceManager. One of them, is if you need pixel level access to your bitmap.

Source code for this article

No comments: