一直不知道自定义消息有什么用,这次尝试获益菲浅
写了一个带进度条的状态条类
/
// CProgStatusBar window
class CProgStatusBar : public CStatusBar
{
DECLARE_DYNAMIC(CProgStatusBar)
CProgressCtrl m_wndProgBar; // the progress bar
// Construction
public:
CProgStatusBar();
// Attributes
public:
// Operations
public:
CProgressCtrl& GetProgressCtrl()
{return m_wndProgBar;}
void OnProgress(UINT pct);
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CProgStatusBar)
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CProgStatusBar();
// Generated message map functions
protected:
//{{AFX_MSG(CProgStatusBar)
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnSize(UINT nType, int cx, int cy);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
void OnProgress(UINT pct);
是处理显示给定进度pct
的函数,它就是我们真正消息的处理者。
2
,定义消息的接收者
#include "ProgStatusBar.h"
class CMainFrame : public CframeWnd
在这个类里:
// Generated message map functions
protected:
//{{AFX_MSG(CMainFrame)
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG
afx_msg LRESULT OnProgress(WPARAM wp, LPARAM lp);
DECLARE_MESSAGE_MAP()
这是自定义的消息处理函数(实际上是接收函数)
在相应的CPP
中关联消息:
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
//{{AFX_MSG_MAP(CMainFrame)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code !
ON_WM_CREATE()
//}}AFX_MSG_MAP
ON_MESSAGE(MYWM_PROGRESS,OnProgress)
END_MESSAGE_MAP()
以及消息处理函数的定义:
/
// CMainFrame message handlers
LRESULT CMainFrame::OnProgress(WPARAM wp, LPARAM lp)
{
m_wndStatusBar.OnProgress((UINT)wp);
return 0;
}
其实让上面的消息处理函数去处理消息相应的参数
3
,消息的发送者
void CTestDoc::Serialize(CArchive& ar)
{
// CEditView contains an edit control which handles all serialization
//
((CEditView*)m_viewList.GetHead())->SerializeRaw(ar);
CWnd* pFrame = AfxGetMainWnd();
if (!ar.IsStoring())
{
for (int pct=10; pct<=100; pct+=10)
{//对文档装载进行仿真处理;
Sleep(150);
if (pFrame)
pFrame->SendMessage(MYWM_PROGRESS, pct);
}
}
if (pFrame)
pFrame->SendMessage(MYWM_PROGRESS, 0);
((CEditView*)m_viewList.GetHead())->SerializeRaw(ar);//显示文本文件的内容;
}
总结一下:
目的:程序运行的时候即要处理任务,又要知道任务进度,两者互不影响。如果没有消息我就不知道该如何做。
实现:void CTestDoc::Serialize(CArchive& ar)中在处理任务同时发送消息,告知外界进度。
afx_msg LRESULT OnProgress(WPARAM wp, LPARAM lp);接收消息,并将参数给m_wndStatusBar.OnProgress((UINT)wp);进行处理。
这就是两个工作同时处理,我不知道该不该成做多任务,并行什么的,因为是外行,定义不清楚。
两外,还可以使用
RegisterWindowMessage和ON_REGISTERED_MESSAGE(WM_USERDEFMSG, OnUserDefMsg)方式更好,不过原理都一样。
这是我第一次有一点理解消息的作用了。感觉还不错,就发上来了。