Tuesday, December 29, 2009

WPF Image and HDC

I had a DLL exporting a function drawing to a HDC. I needed to use that function in my WPF application. This solution needs a reference to System.Drawing.

  1. System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(100, 100);  
  2. using (var g = System.Drawing.Graphics.FromImage(bmp))  
  3. {  
  4.   IntPtr hdc = g.GetHdc();  
  5.   //use hdc to draw here  
  6. }  
  7. var img = new System.Windows.Controls.Image  
  8. {  
  9.   Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap  
  10.   (  
  11.     bmp.GetHbitmap(),   
  12.     IntPtr.Zero,   
  13.     Int32Rect.Empty,  
  14.     System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()  
  15.   )  
  16. };  
  17. //use img in wpf  

1 comment:

  1. Thank you for your code! It helped me migrating code from WinForms to WPF.

    ReplyDelete