WM_USER与WM_APP
⭐ 为了防止用户自定义消息ID与系统消息ID冲突,Microsoft定义了宏WM_USER,小于WM_USER的ID被系统使用,大于MW_USER 的ID被用户使用。 |
范围 | 含义 |
0 到 WM_USER –1 | 系统预留使用的消息,例如WM_PAINT、WM_HSCROLL |
WM_USER到 0x7FFF | 用于用户私有窗口消息 |
WM_APP(0x8000)到0xBFFF | 用于程序的消息传递 |
0xC000到0xFFFF | 使用用户通过调用RegisterWindowMessage注册的字符串消息 |
大于0xFFFF | 预留用于未来扩展消息 |
- WM_USER消息通常用于在开发控件时实现控件特定的消息。如果您已经开发了图像编辑控件,并且需要允许控件的用户设置图像,例如
#define IECM_SETIMAGE (WM_USER+1) // image editor control message. |
- WM_APP消息通常用于实现应用程序级逻辑。如果您要向应用程序发送特定消息以执行操作,例如
#define IEAM_SHOWTOOLBAR (WM_APP+1) // image editor app message |
个人理解,最好去遵守这种规则,否则MSG ID一旦重复就会带来意想不到的后果。举个例子:
一个MFC的对话框程序,有主对话框A和子对话框B。当A、B都需要和theApp通讯时,理想情况下,自定义的消息ID都应该是WM_APP+x。当然你也可以在A中向theApp发送ID为WM_APP+167的msg,在B中向theApp发送ID为WM_USER+167的msg,这时theApp中都可以正常收到A、B发来的消息。但是如果,你的B对话框日后交给别人来维护,他恰好需要向A对话框发消息,恰好也用了WM_USER+167做msg ID,那么此时A是收不到B发过来的这个消息的,这个消息会被theApp截掉。
RegisterWindowMessage
⭐ 定义一个新的窗口消息,并保证该消息在系统范围内是唯一的。 |
- 返回值应该是0xC000到0xFFFF之间的值,为零表示注册消息失败
The RegisterWindowMessage function is typically used to register messages for communicating between two cooperating applications. # RegisterWindowMessage通常是为了在2个协作进程之间进行通信注册信息用的。 If two different applications register the same message string, the applications return the same message value. The message remains registered until the session ends. # 如果2个不同的进程注册了相同的字符串,那么将返回相同的消息ID,并一直保持到进程结束。 Only use RegisterWindowMessage when more than one application must process the same message. For sending private messages within a window class, an application can use any integer in the range WM_USER through 0x7FFF. (Messages in this range are private to a window class, not to an application. For example, predefined control classes such as BUTTON, EDIT, LISTBOX, and COMBOBOX may use values in this range.) # 只有当多个进程需要处理同一消息时才使用RegisterWindowMessage,如果是在一个窗口类中处理私有消息,程序可使用WM_USER+x(这个范围内的消息专用于窗口类的控件,如按钮、编辑栏、列表等,而不是用于应用本身) |
通俗理解,你可以认为RegisterWindowMessage是进程间通讯的方式之一。