如何将非托管C++表单嵌入到.NET应用程序中?

Eve*_*ett 5 .net c# c++ unmanaged

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

为了澄清,原始表单已经在Borland C++项目中用作嵌入式控件.它基本上看起来像一个自定义控件,坐在应用程序中的面板上.

当我说'嵌入'时,我的意思是将INTO放在一个表单中,就像将按钮,面板等放到表单上一样.我不打算做个孩子.

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

al_*_*iro 4

是的,您只需要使用 user32.dll 中的一些低级 win32 函数: SetParent、GetWindowLog、SetWindowLong 、 MoveWindow 。您可以创建一个空的.NET容器控件,将本机窗口的父级设置为.NET控件,然后(可选)修改窗口样式(即删除本机窗口的边框),注意将其大小与.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);

}
Run Code Online (Sandbox Code Playgroud)

然后重写 .NET 控件的 WndProc 以使其适当地调整本机窗体的大小 - 例如填充客户区域。

 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;

        }

 }
Run Code Online (Sandbox Code Playgroud)