xaut3 发表于 2010-5-8 00:24:14

在两个不同的程序实例中发送消息,相互通信 不错的代码结构

有时候,我们需要让不同的应用程序实例间相互发送消息,比如,为了确保对于同一个应用程序,只运行一个的实例,在启动程序时,先检测是否已有此程序的实例运行,如果有,则给此实例发送消息,通知它激活并保持最前,已提醒用户此程序已经在运行。
利用Win32 API RegisterWindowMessage()可以实现这一功能。1.要点[*]用Win32 API RegisterWindowMessage()注册生成一个消息,此消息在整个Session中保持唯一,因此可用于同一个Session中不同的应用程序实例相互通信;[*]用PostMessage或SendMessage广播此消息;[*]需要接收处理此消息的程序实例,使用ON_REGISTERED_MESSAGE()宏接收处理此广播消息;2.实现代码1: //Define a unique const string to create the broadcast message2: //We can use the GuidGen tool to make sure this string is a unique one3: const static LPCTSTR g_AciveMsgName = _T("DBCAAC01-2744-43EE-9FFC-7CD41C672842");4:   5: //Generate a broadcast message6: UINT broadcastMsg = ::RegisterWindowMessage(g_AciveMsgName);7:   8: //Broadcast message9: ::PostMessage(HWND_BROADCAST,broadcastMsg,0,0); 10:11: //Receive and process this message,if the receiver 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: void CDlg::OnActiveWnd() 22: { 23:         // Do something to response this broadcasted message 24:         //...... 25: }
页: [1]
查看完整版本: 在两个不同的程序实例中发送消息,相互通信 不错的代码结构

招聘斑竹