2024年5月17日发(作者:)
c语言mfc的两个界面间的通信
在 C 语言 MFC 中实现两个界面间的通信,通常可以使用消息映射机制或窗口句柄来进
行通信。下面是一个简单的示例,演示了如何在 MFC 中实现两个界面间的通信:
```cpp
// 主窗口消息
#define WM_MAIN_MSG WM_USER+0x01001
// 子窗口消息
#define WM_SUB_MSG WM_USER+0x02001
// 主窗口消息处理函数
afx_msg LRESULT CMultiWindowsDlg::OnMainMsg(WPARAM wParam, LPARAM lParam)
{
CString* strMsg = (CString*)wParam;
SetDlgItemText(IDC_EDIT1, *strMsg);
return 0;
}
// 子窗口向父窗口发送消息的处理函数
afx_msg LRESULT CMySubDialog::OnSubMsg(WPARAM wParam, LPARAM lParam)
{
CString* strMsg = (CString*)wParam;
SetDlgItemText(IDC_EDIT1, *strMsg);
return 0;
}
// 打开子窗口
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);
}
// 向父窗口发送消息
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);
}
```
上述代码中,通过在主窗口中声明一个消息`WM_MAIN_MSG`,并在子窗口中声明一个消
息`WM_SUB_MSG`,实现了两个窗口之间的通信。
发布者:admin,转转请注明出处:http://www.yc00.com/web/1715906559a2690001.html
评论列表(0条)