gpt4 book ai didi

c# - 如何将非托管 C++ 窗体嵌入到 .NET 应用程序中?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:31:55 24 4
gpt4 key购买 nike

我已经能够成功包装我的非托管 Borland C++ dll,并从 C# .NET 4.0 应用程序启动它的表单。是否可以将表单从 dll 直接嵌入到 .NET 应用程序中?

需要澄清的是,原始表单已经在 Borland C++ 项目中用作嵌入式控件。它本质上看起来像一个自定义控件,位于应用程序的面板上。

当我说“嵌入”时,我的意思是将按钮、面板等放置到表单中的方式与将按钮、面板等放置到表单中的方式相同。我不想只制作一个子表格。

如果这不可能,那么也许更好的问题是如何将不受管理的自定义控件嵌入到 .Net 应用程序中?

最佳答案

是的,您只需要使用 user32.dll 中的一些低级 win32 函数:SetParent、GetWindowLog、SetWindowLong、MoveWindow。可以创建一个空的.NET容器控件,将 native 窗口的父级设置为.NET控件,然后(可选)修改窗口样式(即去除 native 窗口的边框),注意与.NET 控件。请注意,在托管级别,.NET 控件将不知道它有任何子控件。

在 .NET 控件中做类似的事情

public void AddNativeChildWindow(IntPtr hWndChild){

//adjust window style of child in case it is a top-level window
int iStyle = GetWindowLong(hWndChild, GWL_STYLE);
iStyle = iStyle & (int)(~(WS_OVERLAPPEDWINDOW | WS_POPUP));
iStyle = iStyle | WS_CHILD;
SetWindowLong(hWndChild, GWL_STYLE, iStyle);


//let the .NET control be the parent of the native window
SetParent((IntPtr)hWndChild, this.Handle);
this._childHandle=hWndChild;

// just for fun, send an appropriate message to the .NET control
SendMessage(this.Handle, WM_PARENTNOTIFY, (IntPtr)1, (IntPtr)hWndChild);

}

然后覆盖 .NET 控件的 WndProc 以使其适本地调整 native 窗体的大小——例如填充客户区。

 protected override unsafe void WndProc(ref Message m)
{

switch (m.Msg)
{
case WM_PARENTNOTIFY:
//... maybe change the border styles , etc
break;
case WM_SIZE:
iWid =(int)( (int)m.LParam & 0xFFFF);
iHei= (int) (m.LParam) >> 16;
if (_childHandle != (IntPtr)0)
{

MoveWindow(_childHandle, 0, 0, iWid, iHei, true);

}
break;

}

}

关于c# - 如何将非托管 C++ 窗体嵌入到 .NET 应用程序中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5156794/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com