问题
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:
- Create a WindowInteropHelper instance (providing the main Window as a constructor parameter).
- Get the value of the Handle property from that WindowInteropHelper instance.
- 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