From 3109a2ebbf6001dc8ac0744133e4f6aae74b7447 Mon Sep 17 00:00:00 2001 From: dahall Date: Sun, 24 Jan 2021 18:58:16 -0700 Subject: [PATCH] Fixed disposal bug in BasicMessageWindow --- PInvoke/User32/BasicMessageWindow.cs | 32 +++++++++++--------------------- 1 file changed, 11 insertions(+), 21 deletions(-) diff --git a/PInvoke/User32/BasicMessageWindow.cs b/PInvoke/User32/BasicMessageWindow.cs index 264408f9..db1703ae 100644 --- a/PInvoke/User32/BasicMessageWindow.cs +++ b/PInvoke/User32/BasicMessageWindow.cs @@ -24,7 +24,7 @@ namespace Vanara.PInvoke /// public class BasicMessageWindow : MarshalByRefObject, IDisposable, IHandle { - private SafeHWND hwnd; + private readonly SafeHWND hwnd; private bool isDisposed; /// Initializes a new instance of the class. @@ -32,7 +32,7 @@ namespace Vanara.PInvoke public BasicMessageWindow(BasicMessageWindowFilter callback = null) { MessageFilter = callback; - ClassName = $"MessageWindowBase+{Guid.NewGuid()}"; + ClassName = $"{GetType().Name}+{Guid.NewGuid()}"; hwnd = CreateWindow(); } @@ -68,9 +68,10 @@ namespace Vanara.PInvoke /// protected virtual SafeHWND CreateWindow() { - if (0 == RegisterClassEx(new WNDCLASSEX { cbSize = (uint)Marshal.SizeOf(typeof(WNDCLASSEX)), lpfnWndProc = WndProc, hInstance = GetModuleHandle(), lpszClassName = ClassName })) - Win32Error.ThrowLastError(); - return Win32Error.ThrowLastErrorIfInvalid(CreateWindowEx(lpClassName: ClassName, lpWindowName: ClassName, hWndParent: HWND.HWND_MESSAGE)); + var hInst = GetModuleHandle(); + var wcx = new WNDCLASSEX { cbSize = (uint)Marshal.SizeOf(typeof(WNDCLASSEX)), lpfnWndProc = WndProc, hInstance = hInst, lpszClassName = ClassName }; + var atom = Win32Error.ThrowLastErrorIfNull(Macros.MAKEINTATOM(RegisterClassEx(wcx))); + return Win32Error.ThrowLastErrorIfInvalid(CreateWindowEx(lpClassName: atom, hWndParent: HWND.HWND_MESSAGE, hInstance: hInst)); } /// Releases unmanaged and - optionally - managed resources. @@ -81,27 +82,16 @@ namespace Vanara.PInvoke { if (isDisposed) return; - isDisposed = true; - hwnd?.Dispose(); - + hwnd?.Dispose(); // Calls DestroyWindow UnregisterClass(ClassName, GetModuleHandle()); ClassName = null; } - private IntPtr WndProc(HWND hwnd, uint msg, IntPtr wParam, IntPtr lParam) - { - IntPtr ret; - if (!(MessageFilter is null) && MessageFilter.Invoke(hwnd, msg, wParam, lParam, out var lRet)) - ret = lRet; - else - ret = DefWindowProc(hwnd, msg, wParam, lParam); - - if (msg == (uint)WindowMessage.WM_NCDESTROY) - Dispose(true); - - return ret; - } + private IntPtr WndProc(HWND hwnd, uint msg, IntPtr wParam, IntPtr lParam) => + MessageFilter is null || !MessageFilter.Invoke(hwnd, msg, wParam, lParam, out var lRet) + ? DefWindowProc(hwnd, msg, wParam, lParam) + : lRet; } } \ No newline at end of file