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?
If you have the window handle (
HWND) of your WPF window, presumably obtained using theWindowInteropHelperclass, 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.Drawingnamespace, and in particular, theGraphicsclass. So all you need to do is add a reference toSystem.Drawingto your WPF application, and you’ll get all of this wrapped functionality for free.The part you’re interested in is the
Graphics.FromHwndmethod, which creates a newGraphicsobject from the specified window handle (HWND).Once you’ve got that, you can obtain a handle to a device context (
HDC) by calling theGraphics.GetHdcmethod, which returns exactly what you’re after—anIntPtrvalue that represents a handle to a device context.Remember that you’ll need to call the
Disposemethod on yourGraphicsobject after you’re finished with it in order to release its associated resources.