Getting Started : Chapter 6 Porting MFC Controls to the .NET® Platform with PInvoke : Migrating From MFC to .NET
Migrating From MFC to .NET
This approach for exchanging data between managed and unmanaged parts of the project uses PInvoke in .NET to access native APIs in dynamic link libraries (DLLs). Additionally, we will explain a method for placing an MFC control into a WinForm project. The procedure is simple:
1. Place the control onto an MFC dialog.
2. Prepare a regular DLL with the dialog and call it as a modeless dialog, adding the following code into the DLL (MFC part of the project):
 
extern "C" __declspec(dllexport) int CallDlg( HWND hWndParent
)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
pDlg = new CMyDialog ( CWnd::FromHandle( hWndParent ) );
pDlg->Create(IDD_DIALOG);
return 0;
}
int CMyDlgApp::ExitInstance()
{
delete pDlg;
return CWinApp::ExitInstance();
}
3. Choose the CHILD style in the dialog properties.
4. Pass the WinForm handle into the dialog's constructor.
5. Add an attribute and a function declaration in the C# program:
 
[DllImport("MyDlg.dll")]
public static extern int CallDlg( int hWnd );
The following code is used to call a modeless MFC dialog from the C# program:
 
private void Form1_Activated(object sender, System.EventArgs e)
{
if (bFirst == true)
{
CallDlg(this.Handle.ToInt32());
bFirst = false;
}
}
6. Override the appropriate handlers to adjust reactions to mouse and keyboard messages.
The procedure described in this section is a common method for placing an MFC-based control onto a WinForm, calling it as a modeless dialog. The following examples apply this procedure to dialog applications that wrap both the Objective Views and the Objective Grid components.