Tag: MFC, message handling, Windows messages

  • How Do You Handle Messages in MFC?

    Message handling in MFC is based on the Windows message-passing mechanism. Windows messages are sent to windows (controls, dialogs, etc.), which are processed by message maps.

    Message maps in MFC link Windows messages to handler functions using macros like ON_COMMAND and ON_WM_PAINT.

    BEGIN_MESSAGE_MAP(CMyWindow, CWnd)
        ON_COMMAND(ID_FILE_NEW, &CMyWindow::OnFileNew)
        ON_WM_PAINT()
    END_MESSAGE_MAP()
    
    void CMyWindow::OnFileNew()
    {
        // Handle the File New command
    }
    
    void CMyWindow::OnPaint()
    {
        //
        CPaintDC dc(this); // Paint device context
        // Custom drawing code
    }
    

    In this example, OnFileNew handles a menu command, while OnPaint is triggered during the window’s paint event.

    Messages are processed in the application’s main message loop and dispatched to the appropriate window for handling.