Click here to Skip to main content
Click here to Skip to main content

Using WinForms controls in an MFC dialog

, 20 Dec 2005 CPOL
Rate this:
Please Sign up or sign in to vote.
This article is a simple introduction to using the CWinFormsControl MFC class to put a Windows Forms control on an MFC dialog.

Introduction

A few days ago, someone asked on the Code Project VC++ forum whether he can use the Dundas WinForms controls on his MFC dialogs. The answer is - yes, that's entirely possible, and pretty easy to do with VC++ 2005.

This article is a simple introduction to using the CWinFormsControl MFC class to put a Windows Forms control on an MFC dialog. The article demonstrates this using a small dialog based application that has a .NET MaskedTextBox control placed on it. The MaskInputRejected event is handled through a function declared in the MFC dialog class.

Steps to put the .NET control in the MFC dialog

  1. Create a fresh MFC dialog based application using VC++ 2005. And turn on /clr compilation.

  2. Add the following header file include to your stdafx.h

    #include <afxwinforms.h>
  3. Modify your dialog resource so it has the controls shown in the screenshot above, with one change. Where you see the MaskedTextBox control in the screenshot, put a static control. You should end up with the following controls.

    IDC_MASKED_EDIT1 We'll map this to the MaskedTextBox control
    IDC_EDITMASK CEdit m_Mask
    IDC_BUTTONMASK ON_BN_CLICKED -> OnBnSetMask
    IDC_EDIT_STATUS CEdit m_StatusEdit (DDX)
    IDC_STATIC "Set Mask"
    IDC_STATIC "Enter Text"
    Table 1 : The controls that you need to add to the dialog resource
  4. Add the CWinFormsControl variable to your dialog header file :

    CWinFormsControl<System::Windows::Forms::MaskedTextBox> m_MaskedEdit;

    The CWinFormsControl class provides the functionality to host a .NET control in an MFC application.

  5. In your dialog class's DoDataExchange, add a call to DDX_ManagedControl :

    void CDialogFormsDlg::DoDataExchange(CDataExchange* pDX)
    {
        CDialog::DoDataExchange(pDX);
        DDX_ManagedControl(pDX, IDC_MASKED_EDIT1, m_MaskedEdit);
    . . .
    }

    This creates the .NET control and associates it with that resource ID.

  6. Add the event handler declaration your header file.

    void OnMaskInputRejected(System::Object^, 
        System::Windows::Forms::MaskInputRejectedEventArgs^);
  7. Setup the delegate map in a public section of your dialog class declaration.

    BEGIN_DELEGATE_MAP( CDialogFormsDlg )
        EVENT_DELEGATE_ENTRY( OnMaskInputRejected, System::Object^, 
            System::Windows::Forms::MaskInputRejectedEventArgs^ )
    END_DELEGATE_MAP()

    The delegate map allows us to use an MFC class function as a delegate by calling MAKE_DELEGATE on it.

  8. Setup the OnBnSetMask function.

    void CDialogFormsDlg::OnBnSetMask()
    {
       CString strMask; 
       m_Mask.GetWindowText(strMask);
       m_MaskedEdit->Clear();
       m_MaskedEdit->Mask = gcnew System::String(strMask);
    }
  9. Setup the MaskedTextBox control in OnInitDialog.

    m_MaskedEdit->PromptChar = L' ';
    m_Mask.SetWindowText(L"00/00/0000");
    OnBnSetMask();
    m_MaskedEdit->MaskInputRejected +=
        MAKE_DELEGATE( System::Windows::Forms::MaskInputRejectedEventHandler, 
        OnMaskInputRejected);
  10. Add the OnMaskInputRejected function to the dialog class.

    void CDialogFormsDlg::OnMaskInputRejected(System::Object^, 
        System::Windows::Forms::MaskInputRejectedEventArgs^ args)
    {
      if(m_MaskedEdit->MaskFull)
      {
        m_StatusEdit.SetWindowText(L"You've hit the max length of the mask.");
      }
      else if(args->Position == m_MaskedEdit->Mask->Length)
      {
        m_StatusEdit.SetWindowText(L"You are at the end of the mask.");
      }
      else
      {
        m_StatusEdit.SetWindowText(L"Bad entry. Check your input!");
      }  
    }
  11. That's it. We are all done. Build and run the application. What you see is an MFC dialog that contains a WinForms control.

Conclusion

This should help you reuse your existing MFC applications and at the same time use new hyper looking .NET UI controls that are released in the market. Please use the article forum to provide feedback about the article or to post any questions you may have.

History

  • Dec 20, 2005 - First published.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Nish Sivakumar

United States United States
Nish is a real nice guy who has been writing code since 1990 when he first got his hands on an 8088 with 640 KB RAM. Originally from sunny Trivandrum in India, he has been living in various places over the past few years and often thinks it’s time he settled down somewhere.
 
Nish has been a Microsoft Visual C++ MVP since October, 2002 - awfully nice of Microsoft, he thinks. He maintains an MVP tips and tricks web site - www.voidnish.com where you can find a consolidated list of his articles, writings and ideas on VC++, MFC, .NET and C++/CLI. Oh, and you might want to check out his blog on C++/CLI, MFC, .NET and a lot of other stuff - blog.voidnish.com.
 
Nish loves reading Science Fiction, P G Wodehouse and Agatha Christie, and also fancies himself to be a decent writer of sorts. He has authored a romantic comedy Summer Love and Some more Cricket as well as a programming book – Extending MFC applications with the .NET Framework.
 
Nish's latest book C++/CLI in Action published by Manning Publications is now available for purchase. You can read more about the book on his blog.
 
Despite his wife's attempts to get him into cooking, his best effort so far has been a badly done omelette. Some day, he hopes to be a good cook, and to cook a tasty dinner for his wife.

Comments and Discussions

 
QuestionSize of Static Control PinmemberAYDIN EBRAHIMI HOMAY26-Apr-13 22:46 
GeneralRefresh PinmemberMember 12749898-Jun-10 8:16 
GeneralMSDN compiling MFC with /clr Pinmembersolartrain26-Feb-09 5:32 
Questionif included afxwinforms.h; createinstance for component fails. PinmemberNagesh Ainchwar10-Dec-08 19:39 
Hi,
 
I have one dll containing 3 MFC com component and some 2-3 MFC dailog. I want to load one Managed (C#) control in one of the dialog. I have added managed control in MFC dialog, compiler option for file set to /clr. dll created without any error.
 
But when I call CreateInstance for any of the MFC component, it fails saying "0x80040111 ClassFactory cannot supply requested class ". It works fine if i remove managed control from dialog.
 
Further, I investigated and found that whether I add managed control or not it does not have any effect. Only when i include in any file and compile using /clr option; CreateInstance falis with above error. if i remove and keep /clr option then it works fine.
 
your answer will be very helpful for me.
 
Nagesh

GeneralIndexed Property Problem: MFC to .NET PinmemberDin Attarwala18-Nov-08 12:14 
GeneralEditing a cell in DataGridView and alt-tabs away and then back causes hang PinmemberSnakefoot4-Sep-08 1:26 
QuestionHow do I do the same without turning on /clr for the entire project? Pinmemberdulsban118-Jul-08 5:39 
QuestionAccess violation in DLL PinmemberRubio7-Aug-07 1:11 
GeneralRe: Access violation in DLL Pinmembermicroflax15-Apr-08 21:32 
AnswerRe: Access violation in DLL PinmemberMember 12749893-Jun-10 3:09 
QuestionWhen done in MFC ActiveX Controls, Remains Inactive!? Pinmember.Suchit15-Jul-07 23:09 
GeneralToolStrip & Menustrip PinmemberCoolsunil19-Feb-07 19:40 
QuestionEver tried using WinForms controls inside a MFC ActiveX ? Pinmembermykel3-Jan-07 22:44 
GeneralCombining MFC and Winforms Pinmemberbeausmom5-Dec-06 15:26 
GeneralRe: Combining MFC and Winforms PinmemberAamir Butt1-Mar-07 19:34 
QuestionUsing CWinFormsControl in MFC Projects PinmemberSabarish_s22-Nov-06 2:39 
AnswerRe: Using CWinFormsControl in MFC Projects PineditorNishant Sivakumar22-Nov-06 4:49 
Generalsetting /clr for source file only PinmemberDave Calkins8-Sep-06 2:49 
GeneralRe: setting /clr for source file only PinmemberRedjo16-Oct-06 23:25 
QuestionRe: setting /clr for source file only Pinmemberjkhax0r30-Jan-07 5:51 
Generalresult when .NET 2.0 runtime not installed PinmemberDave Calkins7-Sep-06 3:00 
General.Net Framework Pinmemberbcharra20-Jul-06 8:59 
GeneralLockup problem using CWinFormsControl PinmemberJeffBoenig12-Jul-06 10:13 
GeneralRe: Lockup problem using CWinFormsControl PinstaffNishant Sivakumar12-Jul-06 10:23 
GeneralRe: Lockup problem using CWinFormsControl PinmemberJeffBoenig12-Jul-06 10:40 
GeneralRe: Lockup problem using CWinFormsControl PinmemberJerry Jeremiah10-Sep-08 15:53 
Generalproblems with embedding .NET control in header file when calling MFC application is not compiled with /clr Pinmemberraghu venkataraman9-May-06 7:26 
GeneralRe: problems with embedding .NET control in header file when calling MFC application is not compiled with /clr PinstaffNishant Sivakumar12-Jul-06 10:21 
QuestionDatagrid in MFC Dialog PinmemberVanathi.P2-Apr-06 20:47 
AnswerRe: Datagrid in MFC Dialog PinmemberKulch4212-Jun-06 11:02 
GeneralRe: Datagrid in MFC Dialog Pinmemberddillon200513-May-07 19:40 
AnswerRe: Datagrid in MFC Dialog PinmemberSnakefoot4-Sep-08 1:17 
GeneralSemi Blank Control Pinmembertahngarth31-Mar-06 12:05 
QuestionMFC project to Form base project Pinmembermsonawane9-Jan-06 13:35 
AnswerRe: MFC project to Form base project PinstaffNishant Sivakumar10-Jan-06 3:30 
GeneralRe: MFC project to Form base project Pinmembermsonawane10-Jan-06 12:59 
GeneralNice! PinmemberMajid Shahabfar27-Dec-05 4:59 
GeneralRe: Nice! PinstaffNishant Sivakumar29-Dec-05 5:37 
GeneralMicrosoft has provided the easy way again PinmemberAamir Butt22-Dec-05 23:35 
GeneralRe: Microsoft has provided the easy way again PinstaffNishant Sivakumar23-Dec-05 1:09 
GeneralArticle #100 PinmemberJörgen Sigvardsson21-Dec-05 10:21 
GeneralRe: Article #100 PinstaffNishant Sivakumar21-Dec-05 10:32 
GeneralRe: Article #100 PinmemberThatsAlok21-Dec-05 17:50 
GeneralRe: Article #100 PinstaffNishant Sivakumar22-Dec-05 0:45 
GeneralOpenEx function problem Pinmembermhar20-Dec-05 22:20 
GeneralRe: OpenEx function problem PinstaffNishant Sivakumar21-Dec-05 0:55 
GeneralRe: OpenEx function problem Pinmembermhar21-Dec-05 13:23 
GeneralRe: OpenEx function problem PinstaffNishant Sivakumar22-Dec-05 2:14 
GeneralReverse... PinmemberImtiaz Murtaza20-Dec-05 16:53 
GeneralRe: Reverse... PinstaffNishant Sivakumar21-Dec-05 0:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.141022.2 | Last Updated 20 Dec 2005
Article Copyright 2005 by Nish Sivakumar
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid