winapi

How can you tell if SendMessage() was successful (message was delivered)?


Is it possible to determine if a SendMessage() call was successful and delivered my message to the target window?

The SendMessage() description in the Windows API seems quiet on this and only says the following:

The return value specifies the result of the message processing; it depends on the message sent.

This obviously refers to the fact that the return code reflects the value returned by the wndproc of the target window.

But what will the return code be if the message wasn't delivered at all (e.g. due to access control, or due to the window having been destroyed in the meantime)? How can I detect such situations?


Solution

  • if SendMessage fail, it set last win32 error code, which we can get back via call GetLastError(). and returned error code, in case fail, never will be 0 (NOERROR) despite this is clear not documented. but how detect that SendMessage is fail ? here we can not base on return value. but we can SetLastError(NOERROR) before call SendMessage and check GetLastError() after:

    -

        SetLastError(NOERROR);
        LRESULT lr = SendMessageW(hwnd, *, *, *);
        ULONG dwErrorCode = GetLastError();
        if (dwErrorCode == NOERROR)
        {
            DbgPrint("message was delivered (%p)\n", lr);
        }
        else
        {
            DbgPrint("fail with %u error\n", dwErrorCode);
        }