The user control uses m_CmdSrc
, as shown in the following example. To use ICommandTarget you need to add a reference to mfcmifc80.dll.
CWinFormsView handles several of the common MFC view notifications by forwarding them to the managed user control. These notifications include the
To create the MFC host application
-
Open Windows Forms Control Library you created in How to: Create the User Control and Host in a Dialog Box.
-
Add a reference to mfcmifc80.dll, which you can do by right-clicking on the project node in Solution Explorer, selecting Add Reference, and then browsing to Microsoft Visual Studio 8\VC\atlmfc\lib.
-
Open UserControl1.Designer.cs and add the following using statement:
В Copy Code using namespace Microsoft::VisualC::MFC;
-
Also, in UserControl1.Designer.cs, change this line:
В Copy Code partial class UserControl1
to this:
В Copy Code partial class UserControl1 : System.Windows.Forms.UserControl, ICommandTarget
-
Add this as the first line of the class definition for
UserControl1
:В Copy Code private ICommandSource m_CmdSrc;
-
Add the following method definitions to
UserControl1
(we will create the ID of the MFC control in the next step):В Copy Code public void Initialize (ICommandSource cmdSrc) { m_CmdSrc = cmdSrc; // need ID of control in MFC dialog and callback function m_CmdSrc.AddCommandHandler(32771, new CommandHandler (singleMenuHandler)); } private void singleMenuHandler (uint cmdUI) { // User command handler code System.Windows.Forms.MessageBox.Show("Got FILE_NEW"); }
-
Open the MFC application you created in How to: Create the User Control and Host in a Dialog Box.
-
Add a menu option that will invoke
singleMenuHandler
.Go to Resource View (CTRL+SHIFT+E), expand the Menu folder, and then double click on IDR_MFC02TYPE. This displays the menu editor.
Add a menu option at the bottom of the View menu. Save the file.
In Solution Explorer, open the Resource.h file, copy the value for the menu option you just added, and paste that value as the first parameter to the
m_CmdSrc.AddCommandHandler
call in the C# project'sInitialize
method. -
Build and run the project.
On the Build menu, click Build Solution.
On the Debug menu, click Start without debugging.
Select the menu option you added. Notice that the method in the .dll is called.