Small MFC Note: Sons window delivery message

First, demand

MFC program may have many dialog main dialog box has a son, this article describes the dialog messages between the father and son. It refers to events external events, external notification. For simplicity, only to deliver the message to the child window for the parent window.

Second, the interface

The main interface is a dialog box, on which a the Button, click into the sub-dialog (using a non-modal). There Static Control dialog interface output information. The process is omitted.

Third, the principle

Custom message ID. Message in response to the sub-window, the event initiator used SendMessagefunction to send a message. You can specify the child window handle is sent.

Fourth, the coding

Defined message ID, of WM_USER must be greater than, for convenience, can be defined in the stdafx.h:

#define WM_MY_EVENT (WM_USER + 1086)

Declare the message header in the sub-dialog response function:

afx_msg LRESULT OnMyEvent(WPARAM wParam, LPARAM lParam);

In the sub-dialog implementation file, add a message associated with the response function:

BEGIN_MESSAGE_MAP(CDlgChild, CDialogEx)
    // ...
    ON_MESSAGE(WM_MY_EVENT, OnMyEvent)
END_MESSAGE_MAP()

The same document, implement response function:

// 父窗口发来的消息,进行响应
LRESULT CDlgChild::OnMyEvent(WPARAM wParam, LPARAM lParam)
{
    int* type = (int*)wParam;
    if (*type == 1)
    {
        GetDlgItem(IDC_STC_SET_TIPS)->SetWindowTextW(L"消息类型1");
        m_nWaitReconnect = 1;
    }
    else if (*type == 2)
    {
        GetDlgItem(IDC_STC_SET_TIPS)->SetWindowTextW(L"消息类型2");
    }

    return 0;
}

Sending a message in the main interface implementation code:

int sendtype = 2;
HWND hWnd = m_pDlgChild->GetSafeHwnd(); // 指定子窗口
::SendMessage(hWnd, WM_MY_EVENT, (WPARAM)&sendtype, NULL);

This article is a simple to use, yet complex where there is use.

Published 481 original articles · won praise 244 · Views 1.1 million +

Guess you like

Origin blog.csdn.net/subfate/article/details/103651152