设为首页收藏本站|繁體中文 快速切换版块

 找回密码
 立即加入
搜索
查看: 838|回复: 0

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

[复制链接]
  • TA的每日心情
    慵懒
    2016-4-21 12:07
  • 签到天数: 3 天

    连续签到: 1 天

    [LV.2]偶尔看看I

    累计签到:3 天
    连续签到:1 天
    发表于 2010-5-8 00:24:14 | 显示全部楼层 |阅读模式

    马上加入,结交更多好友,共享更多资料,让你轻松玩转电力研学社区!

    您需要 登录 才可以下载或查看,没有账号?立即加入

    ×
    有时候,我们需要让不同的应用程序实例间相互发送消息,比如,为了确保对于同一个应用程序,只运行一个的实例,在启动程序时,先检测是否已有此程序的实例运行,如果有,则给此实例发送消息,通知它激活并保持最前,已提醒用户此程序已经在运行。/ p" J/ v- u) J$ t4 w( S4 [
    利用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 message  2: //We can use the GuidGen tool to make sure this string is a unique one  3: const static LPCTSTR 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 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: }
    "真诚赞赏,手留余香"
    还没有人打赏,支持一下
    楼主热帖
    帖文化:【文明发帖 和谐互动】 社区精神:【创新、交流、互助、共享】
    您需要登录后才可以回帖 登录 | 立即加入

    本版积分规则

    招聘斑竹

    小黑屋|手机版|APP下载(beta)|Archiver|电力研学网 ( 赣ICP备12000811号-1|赣公网安备36040302000210号 )|网站地图

    GMT+8, 2025-2-24 07:17

    Powered by Discuz! X3.5 Licensed

    © 2001-2025 Discuz! Team.

    快速回复 返回顶部 返回列表