2

我们的一位客户将我们的 WinForms .NET 网格控件 iGrid.NET ( http://www.10tec.com/ ) 与其他 WPF 控件一起托管在 WPF ElementHost 容器中。它可能看起来很奇怪,因为它是 WinForms 表单内 WPF 主机内的 WinForms 控件,但他们别无选择,因为他们使用了其他 WPF 东西(它是 AvalonDock http://avalondock.codeplex.com/对接容器)。

问题是我们的 .NET 数据网格控件的基础结构需要知道父 WinForms 表单,但我们使用的以下构造在这种情况下总是返回 null:

Form myTopLevelOwnerForm = fCurrentGrid.TopLevelControl as Form;

即用于此目的的标准 Control.TopLevelControl 属性返回 null - 尽管在 WPF 主机的情况下很可能应该如此。

问题是:还有其他方法可以从当前控件的代码中了解父窗体吗?比如说,使用 WinAPI 句柄还是更好的其他原生 .NET memebrs?

4

1 回答 1

1

以下代码有效。至少,在我们的项目中:)

// API declaration
[System.Runtime.InteropServices.DllImport("user32.dll", ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern IntPtr GetParent(IntPtr hWnd);

// Main code snippet
Control myTopLevelControl = fOwner.TopLevelControl;

if (myTopLevelControl == null)
{
    IntPtr handle = fOwner.Handle;
    while (true)
    {
        IntPtr parentHandle = GetParent(handle);
        if (parentHandle == IntPtr.Zero)
        {
            myTopLevelControl = Control.FromHandle(handle) as Form;
            break;
        }
        handle = parentHandle;
    }
}
于 2013-01-18T07:43:37.310 回答