77#include < AppInstallerRuntime.h>
88#include < winget/COMStaticStorage.h>
99
10+ using namespace std ::chrono_literals;
11+
1012namespace AppInstaller ::ShutdownMonitoring
1113{
1214 std::shared_ptr<TerminationSignalHandler> TerminationSignalHandler::Instance ()
@@ -102,7 +104,13 @@ namespace AppInstaller::ShutdownMonitoring
102104 // std::thread requires that any managed thread (joinable) be joined or detached before destructing
103105 if (m_windowThread.joinable ())
104106 {
105- m_windowThread.detach ();
107+ if (m_windowHandle)
108+ {
109+ // Inform the thread that it should stop.
110+ PostMessageW (m_windowHandle.get (), WM_DESTROY, 0 , 0 );
111+ }
112+
113+ m_windowThread.join ();
106114 }
107115 }
108116
@@ -214,6 +222,12 @@ namespace AppInstaller::ShutdownMonitoring
214222 return ;
215223 }
216224
225+ // Unregister the window class on exiting the thread
226+ auto classUnregister = wil::scope_exit ([&]()
227+ {
228+ UnregisterClassW (windowClass, hInstance);
229+ });
230+
217231 m_windowHandle = wil::unique_hwnd (CreateWindow (
218232 windowClass,
219233 L" WingetMessageOnlyWindow" ,
@@ -227,26 +241,38 @@ namespace AppInstaller::ShutdownMonitoring
227241 hInstance,
228242 NULL )); /* lpParam */
229243
230- if (m_windowHandle == nullptr )
244+ HWND windowHandle = m_windowHandle.get ();
245+ if (windowHandle == nullptr )
231246 {
232247 LOG_LAST_ERROR_MSG (" Failed creating window" );
233248 return ;
234249 }
235250
236- ShowWindow (m_windowHandle.get (), SW_HIDE);
251+ // We must destroy the window first so that the class unregister can succeed
252+ auto destroyWindow = wil::scope_exit ([&]()
253+ {
254+ DestroyWindow (windowHandle);
255+ });
256+
257+ ShowWindow (windowHandle, SW_HIDE);
237258
238259 // Force message queue to be created.
239260 MSG msg;
240261 PeekMessage (&msg, NULL , WM_USER, WM_USER, PM_NOREMOVE);
241262 m_messageQueueReady.SetEvent ();
242263
243- // Message loop
264+ // Message loop, we send WM_DESTROY to terminate it
244265 BOOL getMessageResult;
245- while ((getMessageResult = GetMessage (&msg, m_windowHandle. get () , 0 , 0 )) != 0 )
266+ while ((getMessageResult = GetMessage (&msg, windowHandle , 0 , 0 )) != 0 )
246267 {
247268 if (getMessageResult == -1 )
248269 {
249270 LOG_LAST_ERROR ();
271+ break ;
272+ }
273+ else if (msg.message == WM_DESTROY)
274+ {
275+ break ;
250276 }
251277 else
252278 {
0 commit comments