新建一个工程,名称为“MultiWindows”,使用 Unicode 编码。具体界面可以如下:
首先添加一个新的窗口并将界面布局为下图,具体方法如下:
在添加好窗口之后还要为这个窗口添加一个类文件,具体方法可如下:
添加完成之后就可以添加消息功能了,这次有所不同的是,在以往的文章里都是只有一个窗口,而消息也都是在一个窗口内。如今变成了两个窗口,为了使两个窗口都知道对方的消息ID是什么,所以决定在.h文件中声明消息ID(以前是在*Dlg.h中声明),具体添加方法如之前的文章所说,只是在声明的时候换一个位置。具体消息为
主窗口消息:
子窗口消息为:
添加完消息之后,可以到 工程名.h 中声明消息ID了。
[cpp] view plaincopyprint?
- #define WM_MAIN_MSG WM_USER+0x01001
- #define WM_SUB_MSG WM_USER+0x02001
#define WM_MAIN_MSG WM_USER+0x01001#define WM_SUB_MSG WM_USER+0x02001
之后再在 工程名Dlg.h 中声明子窗口的窗口句柄变量
为主窗口上的“打开子窗口(&O)”和“向子窗口发送消息(&S)”添加单击代码:
[cpp] view plaincopyprint?
-
- void CMultiWindowsDlg::OnBnClickedButton1()
- {
- if (dlg == NULL)
- {
- dlg = new CMySubDialog();
- dlg->Create(IDD_DIALOG1,this);
- }
-
- if (dlg == NULL) return (void)MessageBox(_T("子窗口的句柄为空!"));
- dlg->ShowWindow(SW_SHOWNORMAL);
- }
-
-
- void CMultiWindowsDlg::OnBnClickedButton2()
- {
- CString strEdit;
- GetDlgItemText(IDC_EDIT1,strEdit);
-
- if (dlg == NULL) return (void)MessageBox(_T("子窗口的句柄为空!"));
- dlg->SendMessage(WM_SUB_MSG,(WPARAM)&strEdit);
- }
// 打开子窗口(&O)void CMultiWindowsDlg::OnBnClickedButton1(){if (dlg == NULL) {dlg = new CMySubDialog();dlg->Create(IDD_DIALOG1,this);}if (dlg == NULL) return (void)MessageBox(_T("子窗口的句柄为空!"));dlg->ShowWindow(SW_SHOWNORMAL);}// 向子窗口发送消息(&S)void CMultiWindowsDlg::OnBnClickedButton2(){CString strEdit;GetDlgItemText(IDC_EDIT1,strEdit);if (dlg == NULL) return (void)MessageBox(_T("子窗口的句柄为空!"));dlg->SendMessage(WM_SUB_MSG,(WPARAM)&strEdit);}
然后给主窗口的
消息添加代码:
[cpp] view plaincopyprint?
- afx_msg LRESULT CMultiWindowsDlg::OnMainMsg(WPARAM wParam, LPARAM lParam)
- {
- CString* strMsg = (CString*)wParam;
- SetDlgItemText(IDC_EDIT1,*strMsg);
- return 0;
- }
afx_msg LRESULT CMultiWindowsDlg::OnMainMsg(WPARAM wParam, LPARAM lParam){CString* strMsg = (CString*)wParam;SetDlgItemText(IDC_EDIT1,*strMsg);return 0;}
以同样的方法给子对话框的"
向父窗口发送消息(&S)"和
消息添加代码
[cpp] view plaincopyprint?
-
- afx_msg LRESULT CMySubDialog::OnSubMsg(WPARAM wParam, LPARAM lParam)
- {
-
- CString* strMsg = (CString*)wParam;
-
-
- SetDlgItemText(IDC_EDIT1,*strMsg);
-
- return 0;
- }
-
-
- void CMySubDialog::OnBnClickedButton1()
- {
-
- CString strEdit;
- GetDlgItemText(IDC_EDIT1,strEdit);
-
-
- HWND hWnd = this->GetParent()->GetSafeHwnd();
-
-
- if (hWnd == NULL) return (void)MessageBox(_T("获得父窗口句柄失败!"));
- ::SendNotifyMessage(hWnd,WM_MAIN_MSG,(WPARAM)&strEdit,NULL);
- }
// 消息代码afx_msg LRESULT CMySubDialog::OnSubMsg(WPARAM wParam, LPARAM lParam){// 将 wParam 强制转换为 CString 类型CString* strMsg = (CString*)wParam;// 设置对话框中编辑框的文本SetDlgItemText(IDC_EDIT1,*strMsg);return 0;}// 向父窗口发送消息(&S)void CMySubDialog::OnBnClickedButton1(){// 获得编辑框中的文本CString strEdit;GetDlgItemText(IDC_EDIT1,strEdit);// 获得父窗口的句柄HWND hWnd = this->GetParent()->GetSafeHwnd();// 向父窗口发送消息if (hWnd == NULL) return (void)MessageBox(_T("获得父窗口句柄失败!"));::SendNotifyMessage(hWnd,WM_MAIN_MSG,(WPARAM)&strEdit,NULL);}