• 11、MFC中自定义消息


    MFC中自定义消息

    消息映射、循环机制是Windows程序运行的基本方式。VC++ MFC 中有许多现成的消息句柄,可当我们需要完成其它的任务,需要自定义消息,就遇到了一些困难。在MFC ClassWizard中不允许添加用户自定义消息,所以我们必须手动在程序中添加相应代码,以便可以象处理其它消息一样处理自定义消息。

    自定义消息的步骤如下(举个例子):

    1)建立Single DocumentMFC Application,工程名为:MyMessage

    2)自定义消息:

    第一步:定义消息

    Resource.h中添加如下代码:

    //推荐用户自定义消息至少是WM_USER+100,因为很多新控件也要使用WM_USER消息。

    #define WM_MY_MESSAGE (WM_USER+100)

    第二步:声明消息处理函数

    选择CMainFrame类中添加消息处理函数

    MainFrm.h文件中,类CMainFrame内,声明消息处理函数,代码如下:

    protect:

        afx_msg LRESULT OnMyMessage(WPARAM wParam, LPARAM lParam);

    第三步:实现消息处理函数

    MainFrm.cpp文件中添加如下代码:

    LRESULT CMainFrame::OnMyMessage(WPARAM wParam, LPARAM lParam)

    {

          //TODO: Add your message handle code

          return 0;

    }

    第四步:在CMainFrame类的消息块中,使用ON_MESSAGE宏指令将消息映射到消息处理函数中

    BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)

        ON_WM_CREATE()

        ON_MESSAGE(WM_MY_MESSAGE,OnMyMessage)

        //ON_REGISTERED_MESSAGE (WM_MY_MESSAGE,OnMyMessage)

    END_MESSAGE_MAP()

     如果用户需要一个定义整个系统唯一的消息,可以调用SDK函数RegisterWindowMessage定义消息:

    Resource.h中将代码

    #define WM_MY_MESSAGE (WM_USER+100)

    替换为:

    static UINT WM_MY_MESSAGE=RegisterWindowMessage(_T("User"));

    并使用ON_REGISTERED_MESSAGE宏指令取代ON_MESSAGE宏指令,其余步骤同上。

    注:如果仍然使用ON_MESSAGE宏指令,compile可以通过,但是无法响应消息。

    当需要使用自定义消息时,可以在相应类中的函数中调用函数PostMessageSendMessage发送消息PoseMessage(WM_MY_MESSAGE,O,O)

    RegisterWindowMessage Function

    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.

    Syntax

    UINT RegisterWindowMessage(          LPCTSTR lpString

        );

    Remarks

    The RegisterWindowMessage function is typically used to register messages for communicating between two cooperating applications.

    If two different applications register the same message string, the applications return the same message value.

    The message remains registered until the session ends.

    //如果两个Application使用相同的string注册message,他们将等到相同的message值,也就是得到相同的message

    参考

    1http://www.cnblogs.com/xulei/archive/2007/11/22/968170.html

    2http://www.cnblogs.com/pbreak/archive/2010/06/05/1752333.html

    3MSDN

    4]孙鑫 《VC++ 深入》

  • 相关阅读:
    学习进度条第一周
    构建之法阅读笔记01
    软件工程个人作业01
    《构建之法》阅读笔记
    Day6:闭包函数、无参装饰器
    Day5:函数参数
    Day4:字符编码与文件处理
    Day3:数据类型(布尔值、集合)
    Day2:数据类型(列表、元组、字典)
    Day1:初识Python
  • 原文地址:https://www.cnblogs.com/mydomain/p/1837103.html
Copyright © 2020-2023  润新知