一个简单的用户自定义消息传参的实例 postMessage 和 SendMessage

1. sendMessage

.h


        afx_msg void OnBnClickedButton1();
afx_msg LONG OnMessageTest(WPARAM wParam, LPARAM lParam);




.cpp

#define  WM_TEST_MESSAGE WM_USER+2120


BEGIN_MESSAGE_MAP(CtestDlg, CDialogEx)
ON_MESSAGE(WM_TEST_MESSAGE, OnMessageTest)//ADY
END_MESSAGE_MAP()



void CtestDlg::OnBnClickedButton1()
{
// TODO: 在此添加控件通知处理程序代码
CString name = L"name1";
CString sex = L"girl";
::SendMessage(m_hWnd, WM_TEST_MESSAGE, (WPARAM)&name, (LPARAM)&sex);

绿色部分是注视

//只能使用SendMessage,因为PostMessage是异步方式,只是将这个消息丢进消息队列,在你调用完成了PostMessage后,对象已经被释放了,在收到的消息地方已经是一个无效的对象了,如果想使用PostMessage那么请使用CString * url = new CString( "消息参数 "); 
::PostMessage(this-> m_hWnd,WM_MYMESSAGE,0,(LPARAM)url);// 发送一个自定义消息 
消息处理函数 

/*
LRESULT CSplitDlg::OnMyMessage(WPARAM wparam,LPARAM lparam) 

CString * str = (CString *)lparam; 
AfxMessageBox(str); 
delete str;//释放参数 
return 1; 

*/



}

LONG CtestDlg ::OnMessageTest(WPARAM wParam, LPARAM lParam)
{
CString* name = (CString* ) wParam;
CString *sex = (CString* )lParam;
CString s = *sex;

MessageBox(L"test successfully");
return 0;
}



2. PostMessage

.h

afx_msg LONG onLogin(WPARAM wParam, LPARAM lParam);
afx_msg void OnBnClickedButton2();



.cpp


#define  WM_ON_LOGIN       WM_USER+2121
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框


struct ErrorInfo 
{
int retCode;
CString desc;
};


enum Error
{
AV_OK = 0, ///< 成功


/*********客户端错误**********/
AV_ERR_FAILED = 1,///< 一般错误。
};


BEGIN_MESSAGE_MAP(CtestDlg, CDialogEx)

ON_MESSAGE(WM_ON_LOGIN, onLogin)

END_MESSAGE_MAP()



void CtestDlg::OnBnClickedButton2()
{
// TODO: 
ErrorInfo *pInfo = new ErrorInfo;
pInfo->retCode = AV_ERR_FAILED;
CString desc = L"登录失败";
pInfo->desc = desc;


::PostMessage(m_hWnd, WM_ON_LOGIN, (WPARAM)AV_ERR_FAILED, (LPARAM)pInfo);
}


LONG CtestDlg::onLogin( WPARAM wParam, LPARAM lParam )
{
int retCode = wParam;
if(retCode == AV_OK)
{
}
else
{
ErrorInfo *pinfo = (ErrorInfo *)lParam;
CString errCodeStr;
errCodeStr.Format(_T("登录时出错!错误码:%d, 错误信息:%s."), pinfo->retCode, pinfo->desc);


delete pinfo;
}
return 0;
}



这里主要是看PostMessage()  和 SendMessage(), 异步同步消息的处理问题。 还有对于NEW 出来的东西,记得要delete. 还有传的参数怎么解析出来


你可能感兴趣的:(C++,MFC)