Last active
February 20, 2020 23:50
-
-
Save nvictor/37e0ab13c10d944e63798f3a159e5bf1 to your computer and use it in GitHub Desktop.
Win32 API process messages
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// basic version | |
void process_messages1() { | |
MSG message; | |
BOOL result; | |
// GetMessage() blocks and waits for a message | |
// returns 0 when it sees WM_QUIT | |
// returns -1 when something goes wrong | |
// returns a nonzero when there is a valid message to dispatch | |
while (result = GetMessage(&message, 0, 0, 0)) { | |
if (result != -1) { | |
// There is no TranslateMessage() here | |
// TranslateMessage() converts virtual-key (WM_KEYDOWN) | |
// messages to character messages (WM_CHAR) | |
DispatchMessage(&message); | |
} | |
// Use GetLastError() to get errors | |
} | |
} | |
// Another (useless) version, equivalent to above | |
// using PeekMessage for illustration purpose only | |
void process_messages2() { | |
MSG message; | |
BOOL result; | |
while (1) { | |
// PeekMessage() returns TRUE (1) or FALSE (0) | |
// takes a message structure | |
// the second parameter is a window handle, if NULL | |
// (or 0, which is allowed here), the function polls | |
// any window belonging to current thread | |
// the last parameter specifies how processed messages are handled | |
// the third and fourth parameters are for filtering | |
while (PeekMessage(&message, 0, 0, 0, PM_REMOVE) == FALSE) {} | |
if (message.message == WM_QUIT) | |
break; | |
DispatchMessage(&message); | |
} | |
} | |
#define LEN(array) (sizeof(array) / sizeof((array)[0])) | |
// A version processes available messages but does not wait | |
// for any with PeekMessages | |
void process_messages3() { | |
MSG message; | |
while (1) { | |
BOOL result = FALSE; | |
// Skipping code idea (and buggy value) from Handmade Hero | |
DWORD skip_these[] = { | |
// 0x738 is a buggy message sent on Windows 10 -- is that fixed? | |
0x738, | |
// 0xffffffff is max DWORD | |
0xffffffff | |
}; | |
DWORD range_start = 0; | |
for (u32 index; index < LEN(skip_these); index++) { | |
DWORD skip = skip_these[index]; | |
if ((result = PeekMessage(&message, 0, range_start, skip - 1, PM_REMOVE)) == TRUE) | |
break; | |
range_start = skip + 1; | |
} | |
if (result == FALSE) | |
break; | |
switch (message.message) { | |
// processing code goes here, keyboard, mouse, input recording etc... | |
// Should handle WM_QUIT one way or another | |
case WM_QUIT: { /* global_quit = TRUE; */ } break; | |
default: { DispatchMessage(&message); } break; | |
} | |
} | |
} | |
// THOUGHT: another version is keeping the message loop in a separate thread |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment