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?
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:
SendMessage
fail - value returned by GetLastError()
will be
not 0. (most common in this case ERROR_INVALID_WINDOW_HANDLE
or
ERROR_ACCESS_DENIED
).SendMessage
call, some window procedure
in current thread will be called and
code inside window procedure, set last error to non 0 value. so we
get finally not 0 last error, but not because SendMessage
fail.
distinguish between these two cases very problematic-
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);
}