WPF - Does HwndSource have to be disposed?

大城市里の小女人 提交于 2019-12-10 18:28:58

问题


I'm using HwndSource in a WPF window, which is not the main window, in order to hook 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 not clear about when/should I dispose it. The docs of HwndSource.FromHwnd explains the technique above:

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

  1. Create a WindowInteropHelper instance (providing the main Window as a constructor parameter).
  2. Get the value of the Handle property from that WindowInteropHelper instance.
  3. Pass that HWND value as a parameter to FromHwnd.

And then:

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

(the emphasis is mine)

However, at the HwndSource class doc, we see:

Object Lifetime

An HwndSource is a regular common language runtime (CLR) object, and its lifetime is managed by the garbage collector. Because the HwndSource represents an unmanaged resource, HwndSource implements IDisposable. [...] Calling Dispose explicitly from the interoperating code might be necessary for certain interoperation scenarios.

And regarding the hook:

The actual hooks are held by a weak reference. Therefore, make sure that you manage the lifetime of your hook delegate.

来源:https://stackoverflow.com/questions/36874023/wpf-does-hwndsource-have-to-be-disposed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!