Dealing with HWND in WPF

By | August 2, 2011

If you are trying to run a WPF application, you must remember that WPF content is actually constraint to a single HWND. You could have only a single window handle that represents the entire window, and everything inside it is a bitmap drawn on the WPF canvas. Except Popup (which eventually have its own HWND) no WPF element has its own HWND associated with it.

As a matter of fact, a normal win32 application has several HWND’s, I mean every control has its own HWND and the pixels associated with that HWND isn’t been shared between other elements. But while rendering WPF content, a single Pixel can be shared by multiple UIElement, it cannot have Win32 model applied to it. But as it runs as Win32 application, it needed to have a Window handle associated with it which represents the outer window.
To retrieve the Window handle you can call :

HwndSource source = (HwndSource)HwndSource.FromVisual(this);
IntPtr hWnd = source.Handle;

The above code will retrieve the Window handle associated with your WPF application.
One of the major cases where HWND is really required is with Modal window. In WPF, you might know that you can use the following code to create a modal window :

Window w = new Window();

Now this works weird. Actually the parent window does not have the HWnnd reference to the child window. Thus when you minimize the parent window may sometimes come over the child window. To solve this problem we need to assign the HWND of parent window to the child, so that it acts properly as windows does. To do this, you need these codes :

Window w = new Window();
WindowInteropHelper helper = new WindowInteropHelper(w);
helper.Owner = helper.Handle;

This will ensure that the ShowDialog works well in WPF.

I hope this tip helps you. For further reading, follow this link.
Thanks for reading

Author: Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434