只有当我有可见的主窗口时,热键事件才会到达我的应用程序。我正在尝试注册全局热键。当我的应用程序没有运行可见的主窗口时,GetMessage 永远不会返回。我不知道如何解决它。
int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
SetupMainWindow(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
MSG msg;
while (GetMessage(&msg, nullptr, 0, 0) > 0) {
if (msg.message == WM_HOTKEY) {
if (msg.wParam == 1) {
MessageBoxA(nullptr, "Alt-Ctrl-Shift-Up pressed!", "Hello", MB_OK);
printf("Alt-Ctrl-Shift-Up pressed!\n");
}
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
void SetupMainWindow(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
// Step 1: Registering the Window Class
const char CLASS_NAME[] = "HelloWorldClass";
WNDCLASS wc = {};
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
RegisterClass(&wc);
// Step 2: Creating the Window
HWND hwnd = CreateWindowEx(
0, // Optional window styles.
CLASS_NAME, // Window class
"Hello, World!", // Window text
WS_OVERLAPPEDWINDOW, // Window style
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, // Size and position
NULL, // Parent window
NULL, // Menu
hInstance, // Instance handle
NULL // Additional application data
);
RegisterHotKey(nullptr, 1, MOD_ALT | MOD_CONTROL | MOD_SHIFT, VK_UP);
ShowWindow(hwnd, SW_HIDE);
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
switch (uMsg) {
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_PAINT: {
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
TextOut(hdc, 5, 5, "Hello, World!", 13);
EndPaint(hwnd, &ps);
}
return 0;
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
}
这是我当前的代码库。