Click here to Skip to main content
16,022,069 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I have a C# WPF User Control. I want to load that on C++ MFC Dialog.
But the catch is, I do not want to use ActiveX Control.
I want the C# WPF User Control to be COM component and that COM component should be loaded on my other C++ MFC Dialog.

How can this be achieved?

What I have tried:

I created one C# WPF User Control as:
[ComVisible(true)]
[Guid("SomeGUID")]
public partial class UserControl1 : UserControl
{
//My User Control code
}


Registered it using RegAsm.exe <mycsharpwpfusercontroldllname> /codebase /tlb and got the .TLB file out of it.

Later in my C++ MFC Dialog I imported that .TLB file and following is the OnInitDialog of my MFC Dialog.

virtual BOOL OnInitDialog() override
{
    CDialogEx::OnInitDialog();

    // Initialize COM
    CoInitialize(nullptr);

    // Create an instance of the UserControl
    HRESULT hr = m_spUserControl.CreateInstance(__uuidof(UserControl1));
    if (SUCCEEDED(hr))
    {
        // Get the window handle of the UserControl using the GetHandle method
        HWND hWndUserControl = m_spUserControl->GetHandle();

        // Embed the UserControl in the MFC dialog
        CWnd* pWnd = GetDlgItem(IDC_STATIC_USERCONTROL);
        pWnd->Attach(hWndUserControl);
    }

    return TRUE;
}



But some how the above thing is not working.
My MFC dialog application is crashing. I tried to debug, but it is not providing any proper information.
Posted
Comments
[no name] 24-Nov-23 12:27pm    
https://stackoverflow.com/questions/829952/how-do-i-host-wpf-content-in-mfc-applications
Andre Oosthuizen 24-Nov-23 13:38pm    
Should be the answer Gerry, with minor explanations... Will get my +5
Saurabh Ashtaputre 26-Nov-23 13:03pm    
But I want my C# WPF User Controls to be COM components.
Does this work in that case?

1 solution

When your MFC app crashes it might be related to set STAThreadModel to the correct value for the main executable of the MFC app.

In the Linker->Advanced settings of your project is an option called "CLR Thread Attribute" which must be set to "STA threading attribute".
Source: How do I host WPF content in MFC Applications?[^]

If not MFC app will crash without any obvious reason.
 
Share this answer
 
v2

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900