How to: Sink Windows Forms Events from Native C++ Classes

 

The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com.

The latest version of this topic can be found at How to: Sink Windows Forms Events from Native C++ Classes.

You can enable native C++ classes to receive callbacks from managed events raised from Windows Forms controls or other forms with the MFC macro map format. Sinking events in views and dialogs is similar to doing the same task for controls.

To do this, you need to:

This sample continues the work you did in How to: Do DDX/DDV Data Binding with Windows Forms.

Now, you will associate your MFC control (m_MyControl) with a managed event handler delegate called OnClick for the managed Click event.

To attach the OnClick event handler:

  1. Add the following code to the implementation of BOOL CMFC01Dlg::OnInitDialog:

    m_MyControl.GetControl()->button1->Click += MAKE_DELEGATE( System::EventHandler, OnClick );  
    
  2. Add the following code to the public section in the declaration of class CMFC01Dlg : public CDialog.

    // delegate map  
    BEGIN_DELEGATE_MAP( CMFC01Dlg )  
    EVENT_DELEGATE_ENTRY( OnClick, System::Object^, System::EventArgs^ )  
    END_DELEGATE_MAP()  
    
    void OnClick( System::Object^ sender, System::EventArgs^ e );  
    
  3. Finally, add the implementation for OnClick to CMFC01Dlg.cpp:

    void CMFC01Dlg::OnClick(System::Object^ sender, System::EventArgs^ e)  
    {  
        AfxMessageBox(_T("Button clicked"));  
    }  
    

See Also

MAKE_DELEGATE
BEGIN_DELEGATE_MAP
END_DELEGATE_MAP
EVENT_DELEGATE_ENTRY