GetMenuItemCount returning -1 - winapi

Under what conditions the Win32 call GetMenuItemCount can return -1, except of providing an invalid handle to the menu?

All you can assume is that GetMenuItemCount returns -1 on failure.
Specific reasons why this API call can fail are not documented—i.e., they are not part of the published contract. They are implementation details that can change over time, so your code cannot rely upon them.
If you need to get additional information in the event of a failure, call GetLastError as the documentation advises.

Related

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 destoroyed in the meantime)? How can I detect such situations?
There is no way to reliably tell, whether a call to SendMessage succeeded or failed. After all, it only has a single return value, and the entire range of values is used. There is no designated error value.
Playing tricks with the calling thread's last error code won't work either. The scheme proposed in this answer (clearing the last error code prior to the call and evaluating it after the call) is brittle. It's easy to see that it can fail, when sending a message to a window owned by the calling thread (as that window's window procedure is at liberty to change the last error any way it sees fit).
It's not quite as well known, that this can also fail when sending a message to a window owned by a different thread. The code suggests, that no intervening API call can happen in the calling thread. Yet in that scenario, SendMessage will also dispatch incoming cross-thread messages (see When can a thread receive window messages?), allowing the thread's last error code to change.
The only option then is to use SendMessageTimeoutW, as that API reports both the result of the call, as well as an error/success indicator. Passing the SMTO_NOTIMEOUTIFNOTHUNG flag makes sure that an arbitrarily chosen timeout will not adversely affect the outcome.
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:
if SendMessage fail - value returned by GetLastError() will be
not 0. (most common in this case ERROR_INVALID_WINDOW_HANDLE or
ERROR_ACCESS_DENIED).
if we still got 0 as last error - this mean that message was
delivered with no error.
however, possible case, when during 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);
}

What exactly is kqueue's EV_RECEIPT for?

The kqueue mechanism has an event flag, EV_RECEIPT, which according to the linked man page:
... is useful for making bulk changes to a kqueue
without draining any pending events. When passed as input,
it forces EV_ERROR to always be returned. When a filter is
successfully added the data field will be zero.
My understanding however is that it is trivial to make bulk changes to a kqueue without draining any pending events, simply by passing 0 for the nevents parameter to kevent and thus drawing no events from the queue. With that in mind, why is EV_RECEIPT necesary?
Some sample code in Apple documentation for OS X actually uses EV_RECEIPT:
kq = kqueue();
EV_SET(&changes, gTargetPID, EVFILT_PROC, EV_ADD | EV_RECEIPT, NOTE_EXIT, 0, NULL);
(void) kevent(kq, &changes, 1, &changes, 1, NULL);
But, seeing as the changes array is never examined after the kevent call, it's totally unclear to me why EV_RECEIPT was used in this case.
Is EV_RECEIPT actually necessary? In what situation would it really be useful?
If you are making bulk changes and one of them causes an error, then the event will be placed in the eventlist with EV_ERROR set in flags and the system error in data.
Therefore it is possible to identify which changelist element caused the error.
If you set nevents to zero, you get the error code but no indication of which event caused the error.
So EV_RECEIPT allows you to set nevents to a non-zero value without draining any pending events.

In what circumstances would a GetMsgProc functions would receive a code of less than 0?

As the question asks, in what circumstances would the procedure supplied to SetWindowsHookEx with WH_GETMESSAGE as hook ID would receive a "code" parameter less than zero?
The help for the function states :
If code is less than zero, the hook
procedure must pass the message to the
CallNextHookEx function without
further processing and should return
the value returned by CallNextHookEx.
For some reasons, I believe I'm receiving a message with a Code parameter of less than 0 when I would need to actually process the message. Any insight?
Those < 0 codes are used internally to manage the list of hooks (Meaning you should always pass them along without looking at the data!)
See this blog post for details about how people abused the old version and why we now have the Ex versions...

Correct return value of "WindowProc" in a Win32 application

In MSDN's Win32-Api documentation (at http://msdn.microsoft.com/en-us/library/ms633573%28VS.85%29.aspx) on the WindowProc, it states: The return value is the result of the message processing and depends on the message sent.
Since I have to implement this (callback) procedure, I'd like to know what it depends on, and what I have to return. Can someone shed some light on this?
It is dependent on the exact message you are processing. You need to refer to the documentation for that message to see the expected values and meanings of the return value.
For instance, for WM_CREATE, you should return zero to continue window creation, and -1 to fail and destroy the window. For WM_GETICON, you should return a handle to the icon for your window.
For messages that you do not explictly handle, you should call DefWindowProc, passing to it all the parameters to your window proc, and return its return value to the caller.
Michael's answer answers the question perfectly, but just for reference, the usual return value will always be 0.
For most messages it means that your application has processed the message. But always consult the MSDN page for the actual message to know for sure.

Can somebody explain this remark in the MSDN CreateMutex() documentation about the bInitialOwner flag?

The MSDN CreatMutex() documentation (http://msdn.microsoft.com/en-us/library/ms682411%28VS.85%29.aspx) contains the following remark near the end:
Two or more processes can call CreateMutex to create the same named mutex. The first process actually creates the mutex, and subsequent processes with sufficient access rights simply open a handle to the existing mutex. This enables multiple processes to get handles of the same mutex, while relieving the user of the responsibility of ensuring that the creating process is started first. When using this technique, you should set the bInitialOwner flag to FALSE; otherwise, it can be difficult to be certain which process has initial ownership.
Can somebody explain the problem with using bInitialOwner = TRUE?
Earlier in the same documentation it suggests a call to GetLastError() will allow you to determine whether a call to CreateMutex() created the mutex or just returned a new handle to an existing mutex:
Return Value
If the function succeeds, the return value is a handle to the newly created mutex object.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.
If the mutex is a named mutex and the object existed before this function call, the return value is a handle to the existing object, GetLastError returns ERROR_ALREADY_EXISTS, bInitialOwner is ignored, and the calling thread is not granted ownership. However, if the caller has limited access rights, the function will fail with ERROR_ACCESS_DENIED and the caller should use the OpenMutex function.
Using bInitialOwner combines two steps into one: creating the mutex and acquiring the mutex. If multiple people can be creating the mutex at once, the first step can fail while the second step can succeed.
As the other answerers mentioned, this isn't strictly a problem, since you'll get ERROR_ALREADY_EXISTS if someone else creates it first. But then you have to differentiate between the cases of "failed to create or find the mutex" and "failed to acquire the mutex; try again later" just by using the error code. It'll make your code hard to read and easier to screw up.
In contrast, when bInitialOwner is FALSE, the flow is much simpler:
result = create mutex()
if result == error:
// die
result = try to acquire mutex()
if result == error:
// try again later
else:
// it worked!
Well, not sure if there's a real problem. But if you set the argument to TRUE in both processes then you have to check the value of GetLastError() to check if you actually ended up having ownership. It will be first-come-first serve. Useful perhaps only if you use a named mutex to implement a singleton process instance.
The flag is used to create the mutex in an owned state - the successful caller will atomically create the synchronisation object and also acquire the lock before returning in the case that the caller needs to be certain that no race condition can form between creating the object and acquiring it.
Your protocol will determine whether you ever need to do this in one atomic operation.

Resources