Getting Started : Chapter 6 Porting MFC Controls to the .NET® Platform with PInvoke : Objective Views Sample
Objective Views Sample
In the following steps, we port an Objective Views project into a C# project. The related sample is located in <installdir>\Samples\Views\New samples\Objective Views WinForm Sample.
1. Implement your Objective Views project as a dialog-based project.
2. Move the project's files into a regular DLL.
3. Add the C-style APIs into the DLL.
4. Add the C# project to a Visual Studio solution.
5. In the DLL properties, select Linker | Output File and set it to "../SharpTest/bin/Debug/OVDlg.dll". This places the DLL file into the C# project's bin/Debug folder, which allows us to build both projects at once.
6. In the C# code, call the OV project dialog DLL as a child for the WinForm.
7. As an example, you may add button controls to the WinForm, as shown in Figure 20, “Objective Views project as child for Winform.” The Circle and Line buttons are on an MFC dialog that is embedded onto the WinForm. The Circle#, Delete, AddLabel and LabelText buttons are on the WinForm itself.
Figure 20 – Objective Views project as child for Winform
The button AddLabel takes text from the C# code and puts it onto the label of a symbol (that is selected on the canvas) in MFC code. The button LabelText gets text from the label of a symbol selected on the canvas and puts it into a message box in the C# code, as shown in Figure 21, “Using the LabelText Button.” You can also try the Delete, Ctrl+C, Ctrl+X, Ctrl+V keys as well as right-clicking, although you must override a few functions in C# to achieve this functionality.
Figure 21 – Using the LabelText Button
1. Use PInvoke and the Windows API for data exchange between C# and MFC parts of the solution.
2. Override a few functions of WinForm to provide message routing.
3. To run the sample, build OV803d (lib_lib_dbg).
Additional Notes
To access the controller's functions, we use the Windows API SendMessage.
For data exchange, we implement a text buffer in C++. We also use the .NET function StringBuilder for string marshaling in functions GetStrExchange and SetStrExchange.
The ProcessCmdKey, WndProc, and Form1_KeyDown functions in C# have been overridden to provide appropriate handling of mouse and keyboard messages.