Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get HDC from WPF window so that I can draw to it with Gdi+ API?

I have a library that draw on to given HDC using GDI+ apis. I want to use that in a WPF application. I did try getting the handle from WindowInteropHelper class and passing it to the library method which does the drawing. However it fails simply because it cannot create Gdi+ Graphics from that handle.

I then tried using a WinForm element in WindowsFormsHost control and using the HDC available in WinForm control's paint event and it did work fine. What I want to know is can the same thing be made to work directly on WPF control\window? Is there some other way to get the HDC from WPF elements on which GDI draw apis can be used?

like image 235
Nitesh Avatar asked Dec 28 '11 13:12

Nitesh


1 Answers

If you have the window handle (HWND) of your WPF window, presumably obtained using the WindowInteropHelper class, then you can easily obtain a handle to a device context (HDC) for that window.

There are two ways of getting at it, although both ultimately do the same thing. The first is to P/Invoke the necessary GDI+ API functions, but we can rule that out pretty quickly as being unnecessarily time consuming. Remember that the .NET Framework already wraps all this stuff for WinForms development in the System.Drawing namespace, and in particular, the Graphics class. So all you need to do is add a reference to System.Drawing to your WPF application, and you'll get all of this wrapped functionality for free.

The part you're interested in is the Graphics.FromHwnd method, which creates a new Graphics object from the specified window handle (HWND).

Once you've got that, you can obtain a handle to a device context (HDC) by calling the Graphics.GetHdc method, which returns exactly what you're after—an IntPtr value that represents a handle to a device context.

Remember that you'll need to call the Dispose method on your Graphics object after you're finished with it in order to release its associated resources.

like image 122
Cody Gray Avatar answered Sep 21 '22 08:09

Cody Gray