سؤال

One of our customers hosts our WinForms .NET grid control iGrid.NET (http://www.10tec.com/) inside a WPF ElementHost container together with other WPF controls. It may look strange as it's a WinForms control inside a WPF host inside a WinForms form, but they have no choice because of the other WPF stuff they use (it's the AvalonDock http://avalondock.codeplex.com/ docking container).

The problem is that our .NET datagrid control's infrastructure requires to know the parent WinForms form, but the following construction we use for that always return null in this situation:

Form myTopLevelOwnerForm = fCurrentGrid.TopLevelControl as Form;

I.e. the standard Control.TopLevelControl property intended for this purpose returns null - though most likely it should be so in the case of WPF host.

The question is: are there other ways to know the parent form from the current control's code? Say, using WinAPI handles or better other native .NET memebrs?

هل كانت مفيدة؟

المحلول

The following code works. At least, in our project :)

// 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;
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top