![](/img/trans.png)
[英]How do I display vector graphics (SVG) in a Windows Forms application?
[英]How do I display an MFC control in a windows forms application?
我想创建一个窗体控件,它显示一个MFC控件,如CIPAddressCtrl
,带有一个工作的Text属性和TextChanged事件。 如何在Windows窗体应用程序中显示MFC控件? 如果有必要,我很高兴使用C ++ / CLI。
注意:我不是在问如何创建一个全新的Windows窗体控件; 我想在Windows窗体应用程序中托管旧版控件。
本文介绍了一个解决方案,它将包装您的MFC控件。 这个巧妙的技巧是它在Control :: OnHandleCreated的重写中使用了SubclassWindow。 其余代码涉及使用.NET属性手动包装MFC控件的属性。
在我的类似情况下, OnHandleCreated
SubclassWindow
因某些原因无效。 经过一番努力,我得到了它的工作(没有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并初始化控件。 在Dispose上使用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 * 。
编辑: 此相关问题中的代码也使用Attach
/ Detach
。
* 这个例子是我的工作。 (麻省理工学院执照)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.