views:

119

answers:

3

How do I define my own WM (like WM_CLOSE, etc) message that can be handled by the message pump in C++?

If that is even possible.

+2  A: 

Yes you can simply define your own messages as a constant greater than WM_USER:

#define WM_MY_MESSAGE (WM_USER + 1000)

Then you can use the normal ON_COMMAND/ON_NOTIFY macros.

The problem with user defined messages like this is that other programs can use the same constant as you. And you may get a message from someone else for the wrong thing.

To get past this problem you would use registered messages with RegisterWindowMessage.

There's a good rundown on user defined messages/registered messages here.

Brian R. Bondy
Note of course that other programs are not supposed to be sending you messages withing the `WM_USER-0x7FFF` range. Heck, they're not even supposed to be sent _within_ a program. For that you have `WM_APP-0xBFFF range`. The WM_USER is internal to a window class, not a program.
MSalters
+1  A: 

You can use "RegisterWindowMessage" to create new unique messages.

from MSDN : "The RegisterWindowMessage function defines a new window message that is guaranteed to be unique throughout the system. The message value can be used when sending or posting messages."

Max
+2  A: 

It depends on what you are using the message for. This link shows a breakdown of the "address space" for Win32 messages.

WM_USER is not the correct solution in the general case. WM_USER messages "can be defined and used by an application to send messages within a private window class. These values cannot be used to define messages that are meaningful throughout an application, because some predefined window classes already define values in this range."

You are better off assigning a message ID that is in the WM_APP range.

RegisterWindowMessage is useful if you want to have the system assign you a message ID at runtime. "All applications that register the same string can use the associated message number for exchanging messages," so you can use RegisterWindowMessage when you need to use a custom message for simple inter-process communication.

Aaron Klotz