Click here to Skip to main content
6,596,602 members and growing! (19,366 online)
Email Password   helpLost your password?
Desktop Development » Miscellaneous » Windows Forms     Beginner License: The Code Project Open License (CPOL)

Using WinForms controls in an MFC dialog

By Nishant Sivakumar

This article is a simple introduction to using the CWinFormsControl MFC class to put a Windows Forms control on an MFC dialog.
C++/CLI, VC8.0, Windows, .NET, Visual Studio, Dev
Posted:20 Dec 2005
Views:76,107
Bookmarked:46 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
26 votes for this article.
Popularity: 6.21 Rating: 4.39 out of 5
3 votes, 11.5%
1

2

3
2 votes, 7.7%
4
21 votes, 80.8%
5

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)

About the Author

Nishant Sivakumar


Member
Nish is a real nice guy living in Atlanta, who has been coding since 1990, when he was 13 years old. Originally from sunny Trivandrum in India, he recently moved to Atlanta from Toronto and is a little sad that he won't be able to play in snow anymore.

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.
Location: United States United States

Other popular Miscellaneous articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 59 (Total in Forum: 59) (Refresh)FirstPrevNext
GeneralMSDN compiling MFC with /clr Pinmembersolartrain6:32 26 Feb '09  
Questionif included afxwinforms.h; createinstance for component fails. PinmemberNagesh Ainchwar20:39 10 Dec '08  
GeneralIndexed Property Problem: MFC to .NET PinmemberDin Attarwala13:14 18 Nov '08  
GeneralEditing a cell in DataGridView and alt-tabs away and then back causes hang PinmemberSnakefoot2:26 4 Sep '08  
QuestionHow do I do the same without turning on /clr for the entire project? Pinmemberdulsban16:39 18 Jul '08  
QuestionAccess violation in DLL PinmemberRubio2:11 7 Aug '07  
GeneralRe: Access violation in DLL Pinmembermicroflax22:32 15 Apr '08  
QuestionWhen done in MFC ActiveX Controls, Remains Inactive!? Pinmember.Suchit0:09 16 Jul '07  
GeneralToolStrip & Menustrip PinmemberCoolsunil20:40 19 Feb '07  
QuestionEver tried using WinForms controls inside a MFC ActiveX ? Pinmembermykel23:44 3 Jan '07  
GeneralCombining MFC and Winforms Pinmemberbeausmom16:26 5 Dec '06  
GeneralRe: Combining MFC and Winforms PinmemberAamir Butt20:34 1 Mar '07  
QuestionUsing CWinFormsControl in MFC Projects PinmemberSabarish_s3:39 22 Nov '06  
AnswerRe: Using CWinFormsControl in MFC Projects PineditorNishant Sivakumar5:49 22 Nov '06  
Generalsetting /clr for source file only PinmemberDave Calkins3:49 8 Sep '06  
GeneralRe: setting /clr for source file only PinmemberRedjo0:25 17 Oct '06  
QuestionRe: setting /clr for source file only Pinmemberjkhax0r6:51 30 Jan '07  
Generalresult when .NET 2.0 runtime not installed PinmemberDave Calkins4:00 7 Sep '06  
General.Net Framework Pinmemberbcharra9:59 20 Jul '06  
GeneralLockup problem using CWinFormsControl PinmemberJeffBoenig11:13 12 Jul '06  
GeneralRe: Lockup problem using CWinFormsControl PinstaffNishant Sivakumar11:23 12 Jul '06  
GeneralRe: Lockup problem using CWinFormsControl PinmemberJeffBoenig11:40 12 Jul '06  
GeneralRe: Lockup problem using CWinFormsControl PinmemberJerry Jeremiah16:53 10 Sep '08  
Generalproblems with embedding .NET control in header file when calling MFC application is not compiled with /clr Pinmemberraghu venkataraman8:26 9 May '06  
GeneralRe: problems with embedding .NET control in header file when calling MFC application is not compiled with /clr PinstaffNishant Sivakumar11:21 12 Jul '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 20 Dec 2005
Editor: Nishant Sivakumar
Copyright 2005 by Nishant Sivakumar
Everything else Copyright © CodeProject, 1999-2009
Web21 | Advertise on the Code Project