Skip to content

Instantly share code, notes, and snippets.

@marler8997
Created August 10, 2023 23:04
Show Gist options
  • Save marler8997/f9349132aa21e3d10e874c16fac82961 to your computer and use it in GitHub Desktop.
Save marler8997/f9349132aa21e3d10e874c16fac82961 to your computer and use it in GitHub Desktop.
Win32 ShellExecute Clears Message Queue?
// Compile from Visual Studio Command Prompt with:
//
// cl main.c
//
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "shell32.lib")
#define UNICODE
#include <windows.h>
#include <stdio.h>
static unsigned DropMessages()
{
unsigned count = 0;
MSG msg;
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
printf(" droping message %d\n", msg.message);
count++;
}
if (count == 0) {
printf(" empty (no messages were dropped)\n");
}
return count;
}
// NOTE: using wWinMain doesn't help
//int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, WCHAR *pCmdLine, int nCmdShow)
int main()
{
//
// Show that the message queue starts out empty
//
printf("dropping messages, it should start out empty:\n");
{
unsigned dropped = DropMessages();
if (dropped != 0) abort();
}
//
// Post a message to the queue and show that it's in there
//
printf("posting message\n");
if (!PostThreadMessage(GetCurrentThreadId(), WM_USER, 0, 0)) {
printf("PostThreadMessage failed, error={}\n", GetLastError());
return -1;
}
printf("dropping messages, it should drop 1:\n");
{
unsigned dropped = DropMessages();
if (dropped != 1) abort();
}
//
// Post a message to the queue, call ShellExecute which clears the queue!?!
//
printf("posting message\n");
if (!PostThreadMessage(GetCurrentThreadId(), WM_USER, 0, 0)) {
printf("PostThreadMessage failed, error={}\n", GetLastError());
return -1;
}
static const int enable_bug = 1;
if (enable_bug) {
printf("calling ShellExecute, this clears the message queue!?!\n");
INT_PTR result = (INT_PTR)ShellExecute(NULL, NULL, NULL, NULL, NULL, 0);
if (result <= 32) {
printf("ShellExecute failed, result={}, error={}\n", result, GetLastError());
return -1;
}
}
printf("dropping messages, you'd think it should have 1 but:\n");
{
unsigned dropped = DropMessages();
if (dropped == 1) {
printf("Success!\n");
} else {
printf("Error: expected to drop exactly 1 message but dropped %d\n", dropped);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment