How To Nonzero Return from SendMessage() with HWND_BROADCAST


The SendMessage() function calls the window procedure for the specified window and does not return until that window has processed the message and returned a value. Applications can send messages to all top-level windows in the system by specifying HWND_BROADCAST as the first parameter to the SendMessage() function. In doing so, however, applications lose access to the return values resulting from the SendMessage() call to each of the top-level windows.

More Information

When a call to SendMessage() is made, the value returned by the window procedure that processed the message is the same value returned from the SendMessage() call.

Among other things, SendMessage() determines whether the first parameter is HWND_BROADCAST (defined as -1 in WINDOWS.H). If HWND_BROADCAST is the first parameter, SendMessage enumerates all top-level windows in the system and sends the message to all these windows. Because this one call to SendMessage() internally translates to a number of SendMessage() calls to the top-level windows, and because SendMessage() can return only one value, Windows ignores the individual return values from each of the top-level window procedures, and just returns a nonzero value to the application that broadcast the message. Thus, applications that want to broadcast a message to all top-level windows, and at the same time expect a return value from each SendMessage() call, should not specify HWND_BROADCAST as the first parameter.

There are a couple of ways to access the correct return value from messages sent to more than one window at a time:

  • If the broadcasted message is a user-defined message, and only a few other applications respond to this message, then those applications that trap the broadcasted message must return the result by sending back another message to the application that broadcast the message. The return value can be encoded into the message's lParam.
  • If the application does not have control over which application(s) will respond to the message, and it still expects a return value, then the application must enumerate all the windows in the system using EnumWindows() function, and send the message separately to each window it obtained in the enumeration callback function.

ID članka: 102588 – Zadnji pregled: 22. apr. 2009 – Revizija: 1

Povratne informacije