Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to use Windows::Forms::UserControl on a CWnd based

0.00/5 (No votes)
22 Oct 2004 1  
This article describes how to place .NET UserControl based classes on a MFC based class.

Introduction

I tried to use a .NET based UserControl within an existing MFC application. First, things
seemed to be easy. But when I tried to add a member to my MFC dialog, I had to recognize,
that things were getting complicated. First I started to write a useful class allowing me
to add a member of any .NET UserControl to MFC applications.

template <class T> class CdotNETCtl
{
public:
    CdotNETCtl(
void)
    {
    };

    ~CdotNETCtl(
void)
    {
    };
            
   
bool Create(CWnd *pWndParent)
    {
       
bool bRetal = false;

       
try
       
{
            m_pCtl = T::Create();
            CWnd* pCtl =
new CWnd();
            m_pCtl->Show();
            pCtl->Attach((HWND)m_pCtl->GetHandle());
            pCtl->SetOwner(pWndParent);
            pCtl->SetParent(pWndParent);
            pCtl->Detach();
            delete pCtl;
            bRetal =
true;
        }
       
catch(...)
        {
        }
       
return bRetal;
    };

    bool Create(CWnd *pWndParent, int X, int Y, int newWidth, int newHeight)
    {
       
bool bRetal = false;

        try
       
{
            m_pCtl = T::Create();
            CWnd* pCtl =
new CWnd();
            m_pCtl->Show();
            pCtl->Attach((HWND)m_pCtl->GetHandle());
            pCtl->SetOwner(pWndParent);
            pCtl->SetParent(pWndParent);
            pCtl->Detach();
            delete pCtl;
            m_pCtl->Left = X;
            m_pCtl->Top = Y;
            m_pCtl->Width = newWidth;
            m_pCtl->Height = newHeight;

            bRetal =
true;
        }
       
catch(...)
        {
        }
       
return bRetal;
    };

    T* operator->()
    {
       
if(!m_pCtl)
        {
           
throw;
        }
       
return m_pCtl;
    }
private:
    gcroot<T*> m_pCtl;
};

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here