WPF - Do I need an HwndSource?

I use HwndSource in a WPF window, which is not the main window, to hook up a window procedure (WndProc) to receive some messages:

 WinSource = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle); WinSource.AddHook(new HwndSourceHook(WndProc)); 

HwndSource implements IDisposable . MSDN is unclear when / if I should use it. The HwndSource.FromHwnd docs explain the technique above:

You can use this method to return an HwndSource for a window that is clearly not an interaction window. The procedure for this:

  • Create an instance of WindowInteropHelper (providing the main window as a constructor parameter).
  • Get the value of the Handle property from this instance of WindowInteropHelper.
  • Pass this HWND value as the FromHwnd parameter.

And then:

This method can be useful if you want to add general AddHook message processing to the window. However , when you create an HwndSource, you are also responsible for destroying it. This is true even if the application object for the HwndSource application is located.

(my emphasis)

However, in the HwndSource doc class, we see:

Object Life

HwndSource is a common CLR runtime object, and its resource is managed by the garbage collector. Because HwndSource is an unmanaged resource, HwndSource implements IDisposable. [...] For certain interaction scenarios, you may need to call Dispose explicitly from the interaction code.

And regarding the hook:

Actual hooks are held by a weak standard. Therefore, make sure that you manage the life of your delegate.

+2
source share

Source: https://habr.com/ru/post/1380615/


All Articles