ConsoleHost.cpp
1 // Copyright (c) Microsoft Corporation 2 // The Microsoft Corporation licenses this file to you under the MIT license. 3 // See the LICENSE file in the project root for more information. 4 5 #include "ConsoleHost.h" 6 #include <iostream> 7 8 bool ConsoleHost::s_exitRequested = false; 9 10 ConsoleHost::ConsoleHost(ModuleLoader& moduleLoader, HotkeyManager& hotkeyManager) 11 : m_moduleLoader(moduleLoader) 12 , m_hotkeyManager(hotkeyManager) 13 { 14 } 15 16 ConsoleHost::~ConsoleHost() 17 { 18 } 19 20 BOOL WINAPI ConsoleHost::ConsoleCtrlHandler(DWORD ctrlType) 21 { 22 switch (ctrlType) 23 { 24 case CTRL_C_EVENT: 25 case CTRL_BREAK_EVENT: 26 case CTRL_CLOSE_EVENT: 27 std::wcout << L"\nCtrl+C received, shutting down...\n"; 28 s_exitRequested = true; 29 30 // Post a quit message to break the message loop 31 PostQuitMessage(0); 32 return TRUE; 33 34 default: 35 return FALSE; 36 } 37 } 38 39 void ConsoleHost::Run() 40 { 41 // Install console control handler 42 if (!SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE)) 43 { 44 std::wcerr << L"Warning: Failed to set console control handler\n"; 45 } 46 47 s_exitRequested = false; 48 49 // Message loop 50 MSG msg; 51 while (!s_exitRequested) 52 { 53 // Wait for a message with a timeout so we can check s_exitRequested 54 DWORD result = MsgWaitForMultipleObjects(0, nullptr, FALSE, 100, QS_ALLINPUT); 55 56 if (result == WAIT_OBJECT_0) 57 { 58 // Process all pending messages 59 while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) 60 { 61 if (msg.message == WM_QUIT) 62 { 63 s_exitRequested = true; 64 break; 65 } 66 67 if (msg.message == WM_HOTKEY) 68 { 69 m_hotkeyManager.HandleHotkey(static_cast<int>(msg.wParam), m_moduleLoader); 70 } 71 72 TranslateMessage(&msg); 73 DispatchMessage(&msg); 74 } 75 } 76 } 77 78 // Remove console control handler 79 SetConsoleCtrlHandler(ConsoleCtrlHandler, FALSE); 80 }