是的,您只需要使用 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);
}
然后重写 .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;
}
}