Introduction
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.
Background
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.
Using the Code
First of all, we need to open two projects, MFC and Windows Form User Control Library, so:
- Open Visual Studio preferably Visual Studio 2012.
- Select File/New Project/Visual C++ and then select MFC application project template.
- Click next and select dialog based in MFC application wizard window and at the finally 'Finish'.
- Right click on project and select properties. Later, you should change Common Language Runtime Support to Common Language Runtime Support (/clr).
- Build your project
- Add the following header file include to your stdafx.h.
#include <afxwinforms.h>
Now, we need to open the second project:
- From the Solution Explorer window, right click on the MFC project solution and select Add/New Project item.
- Select other language/Visual C#/Windows/Windows Forms Control Library.
- Set the project name
WinFormUserControl
and then press OK.
- Right click on the C# project and click properties, change Target Framework to .NET 4 if it is .NET 4.5.
- Right click on the MFC project and click properties, Common Properties/Add New Reference/ Add your C# project DLL from here.
- Add User Control in your project.
- Open your dialog box header file "MFCApplication1Dlg.h" and define
CWinFormsControl
member with this name: "m_ctrl
".
#pragma once
class CMFCApplication1Dlg : public CDialogEx
{
CWinFormsControl<WinFormUserControl::UserControl1> m_ctrl;
public:
CMFCApplication1Dlg(CWnd* pParent = NULL);
enum { IDD = IDD_MFCAPPLICATION1_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX);
protected:
HICON m_hIcon;
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:
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.
History
- April 28, 2013 - First published.