本文主要是介绍MFC实例:[6]SendMessage 发送字符串,结构体,数字,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
MFC实例:[6]SendMessage 发送字符串,结构体,数字
将指定的消息发送到一个窗口或多个窗口。SendMessage为这个指定的消息调用窗口处理程序,直到窗口处理完这个程序后才会返回。和SendMessage函数相比,PostMessage函数发送一个消息到线程消息对列中,并立即返回。
函数原型:B00L SendMessage(HWND hWnd,UINT Msg,WPARAM wParam,LPARAM lParam);
下面分享详细实例:
界面设计如下:
1、发送字符串步骤:
(1)在建好的MFC工程中头文件添加消息定义宏:
#define TTMSG_WARNLIST1 5000 //字符串
#define TTMSG_WARNLIST2 5001 //结构体
#define TTMSG_WARNLIST3 5003 //数字
(2)在对话框文件中添加消息响应:
BEGIN_MESSAGE_MAP(CMFCMessageDlg, CDialogEx)ON_WM_SYSCOMMAND()ON_WM_PAINT()ON_WM_QUERYDRAGICON()ON_MESSAGE(TTMSG_WARNLIST1, &CMFCMessageDlg::OnTTwarnListMsg1)ON_MESSAGE(TTMSG_WARNLIST2, &CMFCMessageDlg::OnTTwarnListMsg2)ON_MESSAGE(TTMSG_WARNLIST3, &CMFCMessageDlg::OnTTwarnListMsg3)
END_MESSAGE_MAP()
(3)在头文件中定义消息响应函数声明:
afx_msg LRESULT OnTTwarnListMsg1(WPARAM wParam, LPARAM lParam);afx_msg LRESULT OnTTwarnListMsg2(WPARAM wParam, LPARAM lParam);afx_msg LRESULT OnTTwarnListMsg3(WPARAM wParam, LPARAM lParam);
2、双击SendMessage字符串按钮,编辑代码,写响应函数:
void CMFCMessageDlg::OnBnClickedButton1()
{// TODO: 在此添加控件通知处理程序代码//字符串数组CString str1 = _T("123");CString str2 = _T("hello");::SendMessage(this->GetSafeHwnd(), TTMSG_WARNLIST1, (WPARAM)(LPCTSTR)str1, (LPARAM)(LPCTSTR)str2); //发送消息方式1// SendMessage(TTMSG_WARNLIST1, (WPARAM)(LPCTSTR)str1, (LPARAM)(LPCTSTR)str2); //发送消息方式2
}LRESULT CMFCMessageDlg::OnTTwarnListMsg1(WPARAM wParam, LPARAM lParam)
{CString cstr1 = (LPCTSTR)wParam;CString cstr2 = (LPCTSTR)lParam;MessageBox(cstr1);MessageBox(cstr2);return TRUE;
}
3、双击SendMessage结构体按钮,编辑代码,写响应函数:
struct _tag_aa
{CString s1;char szBuffer[512];int a;char* szText;
};
void CMFCMessageDlg::OnBnClickedButton2()
{// TODO: 在此添加控件通知处理程序代码_tag_aa *a = new _tag_aa;a->s1 = "AAAAAAAAAAAAAAAAAAAA";strcpy_s(a->szBuffer, "BBBBBBBBBBBBBBBBBBBBBBB);a->szText = "CCCCCCCCCCCCCCCCCCC";a->a = 250;SendMessage(TTMSG_WARNLIST2, (WPARAM)a,0);}
LRESULT CMFCMessageDlg::OnTTwarnListMsg2(WPARAM wParam, LPARAM lParam)
{_tag_aa* pA = (_tag_aa*)wParam;CString str=pA->s1;CString str2 = pA->szBuffer;CString str4 = pA->szText;int b = pA->a;CString str3;str3.Format("%d",b);MessageBox(str3);MessageBox(str+str2+str4);delete pA;return TRUE;}
4、双击SendMessage数字按钮,编辑代码,写响应函数:
void CMFCMessageDlg::OnBnClickedButton3()
{// TODO: 在此添加控件通知处理程序代码int b = 10;SendMessage(TTMSG_WARNLIST3,b,0);
}
LRESULT CMFCMessageDlg::OnTTwarnListMsg3(WPARAM wParam, LPARAM lParam)
{int c = wParam;CString str;str.Format("%d",c);MessageBox(str);return TRUE;
}
注意:将消息发送给哪个窗口,就要获取哪个窗口的句柄,获取句柄方式总结如下:
(1)GetSafehWnd() 取你程序所在窗口类的句柄
(2)GetActiveWindow() 取当前活动窗口句柄
(3)AfxGetMainWnd ()取主窗口句柄
(4)GetForegroundWindow() 取前台窗口句柄
(5)获取控件ID句柄,语法为:GetDlgItem(IDC_Dialog)->m_hWnd :参数为 该控件的ID, 返回值为:CWnd * 类型,但它是CWnd类内的函数,因此要先获取控件所在窗口的指针,如:
::SendMessage(AfxGetMainWnd()->GetDlgItem(IDC_Dialog)->m_hWnd, WM_SETTEXT, 0, (LPARAM)str.GetBuffer(0));
工程地址:
链接:https://pan.baidu.com/s/1KwzxjsjnDkWY8oyPKKdYnA
提取码:5528
这篇关于MFC实例:[6]SendMessage 发送字符串,结构体,数字的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!