Sometimes, we need to make different applicationsProgramInstances send messages to each other. For example, to ensure that only one instance is run for the same application, check whether an instance of this program is running when the program is started. If yes, then, a message is sent to the instance to notify it to activate and maintain the beginning. The user is notified that the program is running.
You can use Win32 API registerwindowmessage () to implement this function.
1. Key Points
- Use the Win32 API registerwindowmessage () to register and generate a message. This message remains unique throughout the session. Therefore, it can be used for communication between different application instances in the same session;
- Use postmessage or sendmessage to broadcast the message;
- The program instance that needs to receive the message and use the on_registered_message () macro to receive and process the broadcast message;
2. Implementation Code
1:// Define a unique const string to create the broadcast message
2:// We can use the guidgen tool to make sure this string is a unique one
3:Const StaticLpctstr g_acivemsgname = _ T ("DBCAAC01-2744-43EE-9FFC-7CD41C672842");
4:
5:// Generate a broadcast message
6: uint broadcastmsg =: registerwindowmessage (g_acivemsgname );
7:
8:// Broadcast message
9: postmessage (hwnd_broadcast, broadcastmsg, 0, 0 );
10:
11:// Receive and process this message, if the specified er is a different app instance, it need
12:// Also to call the: registerwindowmessage (g_acivemsgname) API to get the message code
13:// Note: This message code is assotiated with the global unique string (g_acivemsgname)
14:// And it's allocated by the Windows System
15: begin_message_map (...)
16://......
17: on_registered_message (s_wm_activewnd, onactivewnd)
18://......
19: end_message_map ()
20:
21:VoidCdlg: onactivewnd ()
22 :{
23:// Do something to response this broadcasted message
24://......
25 :}