Sometimes we need to use integration legacy systems with a new technology. In this tip/trick, I will discuss about hosting .NET Windows Form user controls in an MFC dialog box so we can develop our legacy systems in MFC with .NET and related components after that.
In the past if you wanted to use .NET components in your MFC application, you could use COM technology and it would be terrible. But after Visual Studio 2005, Microsoft introduced the C++/CLI technology. With this new technology, developers can use C# or VB.NET and any other language supported with .NET in MFC projects.
First of all, we need to open two projects, MFC and Windows Form User Control Library, so:
#include <afxwinforms.h>
Now, we need to open the second project:
WinFormUserControl
CWinFormsControl
m_ctrl
// MFCApplication1Dlg.h : header file // #pragma once // CMFCApplication1Dlg dialog class CMFCApplication1Dlg : public CDialogEx { CWinFormsControl<WinFormUserControl::UserControl1> m_ctrl; // Construction public: CMFCApplication1Dlg(CWnd* pParent = NULL); // standard constructor // Dialog Data enum { IDD = IDD_MFCAPPLICATION1_DIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: HICON m_hIcon; // Generated message map functions virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); DECLARE_MESSAGE_MAP() };
After that you should go to MFCApplication1Dlg.cpp and override the DoDateExchange method:
DoDateExchange
void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_ManagedControl(pDX,IDC_STATIC,m_ctrl); }
Now it is finished and you can run your project. For more information, click here.