My Windows API callback function isn't executing. What's wrong?

I’m trying to close a program using the Windows API but I’m running into a problem. I’ve set up a callback function that should run after sending a WM_CLOSE message but it’s not working as expected.

Here’s a simplified version of what I’m doing:

#include <windows.h>

VOID CALLBACK MyCallback(HWND hwnd, UINT uMsg, ULONG_PTR dwData, LRESULT lResult) {
    MessageBox(NULL, L"Callback executed", L"Info", MB_OK);
}

int main() {
    HWND targetWindow = FindWindow(NULL, L"Target Program");
    if (targetWindow) {
        SendMessageCallback(targetWindow, WM_CLOSE, 0, 0, MyCallback, 0);
        // Wait a bit to allow for processing
        Sleep(1000);
    }
    return 0;
}

The program finds the window and sends the WM_CLOSE message fine. The target program closes but my callback never runs. I’m pretty sure I’m missing something obvious but I can’t figure out what. Any ideas on why the callback isn’t being called?

I’ve encountered a similar issue before, and it turned out the problem was related to message processing. The callback function might not be executing because the main thread isn’t pumping messages.

Try adding a message loop after sending the message. Something like this:

SendMessageCallback(targetWindow, WM_CLOSE, 0, 0, MyCallback, 0);

MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}

This allows your program to process incoming messages, including the one that triggers your callback. The Sleep() function doesn’t process messages, so it won’t help here.

Also, make sure the target window’s message loop is still running when you send WM_CLOSE. If it exits immediately, your callback might not have a chance to execute. You might want to use PostMessage() instead of SendMessage() to avoid potential deadlocks.

hey mate, i think ur problem might be with the message queue. try adding a message loop after sendin the WM_CLOSE. somethin like:

MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}

this should let ur program process incoming messages and trigger the callback. hope it helps!

The issue likely stems from the message queue not being processed properly. SendMessageCallback is asynchronous, so your program needs to handle incoming messages to trigger the callback. Instead of using Sleep(), implement a message loop:

MSG msg;
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}

This allows your application to process messages, including the one that invokes your callback. Additionally, consider using PostMessage instead of SendMessage to avoid potential deadlocks if the target window’s thread is busy. Remember to handle cases where the target window might close immediately upon receiving WM_CLOSE.