How to use HwndSource

10,632

WPF window is made up of two parts:

  • Window area which is made up of Operating System Window
  • Non - Window area which is inside a WPF window

Now, a WPF window being a ContentControl holds everything as its Content. So you can say every pixel of the Content inside the Window class is held by the Outside window. Every Visual of WPF does not have its own HANDLE associated with it, rather it is a content for the outside window element.

For detail refer to this - http://www.abhisheksur.com/2010/12/win32-handle-hwnd-wpf-objects-note.html

So, when you are disposing that handle, you are actually disposing your main window handler which results in close of complete application.

Hence, you are here only fetching your window handler and not creating anything which you might need to dispose..!!

Share:
10,632
HCL
Author by

HCL

Updated on June 28, 2022

Comments

  • HCL
    HCL almost 2 years

    In a WPF app of mine, I have to let the user choose a certificate. I do this via the X509Certificate2UI.SelectFromCollection-method. For proper dialog handling, the SelectFromCollection-method needs an IntPtr of the parents Hwnd. I have found the following code to provide this:

    HwndSource source = (HwndSource)HwndSource.FromVisual(Window.GetWindow(this));
    var certificates= X509Certificate2UI.SelectFromCollection(...,source.Handle);
    

    So far, this works fine. My question is, because I have no big knowledge of Win32 or interop, if I have to do some cleanup code after this, or if there are some pitfalls in using the HwndSource-class like I did above?

    I have seen that HwndSource implements IDisposable, but disposing the object after use closes the parent window. Therefore this seems not to be the intended usage.