如何显示在Windows窗体应用程序的MFC控制?

问题描述 投票:3回答:2

我想创建一个Windows窗体控件表示一个MFC控件,如CIPAddressCtrl,具有工作Text属性和TextChanged事件。如何显示在Windows窗体应用程序的MFC控制?我很高兴,如果需要使用C ++ / CLI。

注:我不问如何创建一个全新的Windows窗体控件;我想举办一个Windows窗体应用程序的旧有控制。

c# winforms mfc c++-cli
2个回答
5
投票

This article提出了一个解决方案,将包装你的MFC控制。这样做的绝招是其在控制:: OnHandleCreated的清除使用调用SubclassWindow的。的代码的其余部分涉及手动包装用.NET属性的MFC控制的属性。


1
投票

在我类似的情况下,在SubclassWindow OnHandleCreated没有出于某种原因。经过一番挣扎后,我得到了它的工作(不包括C ++ / CLI):

首先,从Form#Handle得到HWND并将它传递给你的MFC DLL。

class GuestControl : Control
{
    private IntPtr CWnd { get; set; }

    public GuestControl()
    {
        CWnd = attach(Handle);
    }

    protected override void Dispose(bool disposing)
    {
       if (disposing)
       {
          detach(CWnd);
       }

       base.Dispose(disposing);
    }

    [DllImport("your_mfc_dll")]
    private static extern IntPtr attach(IntPtr hwnd);
    [DllImport("your_mfc_dll")]
    private static extern void detach(IntPtr hwnd);
}

然后,在你的DLL,CWnd::Attach所得到的HWND并初始化控制。对处置CWnd::Detach清理。

/** Attach to C# HWND and initialize */
extern "C" __declspec(dllexport) CWnd* PASCAL attach(HWND hwnd) {
    auto w = std::make_unique<CWnd>();

    if (!w->Attach(hwnd)) { return nullptr; }

    // ... initialize your MFC control ...

    return w.release();
}

/** Detach and delete CWnd */
extern "C" __declspec(dllexport) void PASCAL detach(CWnd *cwnd) {
    auto w = std::unique_ptr<CWnd>(cwnd);
    w->Detach();
}

GuestControl.cs / guest.cpp *为一个完整的例子。

编辑:在this related question代码还使用Attach / Detach

* The example是我的工作。 (MIT许可证)

© www.soinside.com 2019 - 2024. All rights reserved.