7
votes

I need to be able to get a WinForm dialog's Owner's HWND. In unmanaged I have a background thread that gets the HWND for the window in front. The code then calls ::GetParent(frontHWND) to see if it needs to hide a different non-modal MFC dialog. When the WinForm dialog is the frontHWND, I always get NULL back for the GetParent call. I have also tried GetOwner realizing .Net tried to cleanup the difference between Parent and Owner. Looking at the WinForm dialog w/ Spy++, it also say the WinForm has no parent or owner. I have passed in

NativeWindow ^natWin = gcnew NativeWindow();
natWin->AssignHandle(IntPtr(hwndParent));
managedDlg->ShowDialog(natWin);

The above code didn't set the owner of the WinForm. I tried calling the Win32 SetParent from the WinForm code in OnFormShown(), but the locked up the MFC application and the WinForm.

Can someone explain how to get my unmanaged dialog/app to be the owner/parent of the managed winform?

1
Any information will be helpful... like what ShowDialog(IWin32Window) actually sets. According to this link, link, it should be setting the owner but when I use Spy++ I don't see that.Byron

1 Answers

5
votes

To show a C# form with a C++ parent I do this:

void GUIWrapper(HWND parent)
{
    System::IntPtr myWindowHandle = System::IntPtr(parent);
    System::Windows::Forms::IWin32Window ^w = System::Windows::Forms::Control::FromHandle(myWindowHandle);
    ManagedDialog::ManagedDialogGUI ^d = gcnew ManagedDialog::ManagedDialogGUI();
    d->Show(w);
}

this code is put in a C++/CLI wrapper DLL. Hope this helps.

Edit: "w" must be tested against nullptr, because Control::FromHandle could fail. See here: Why Control.FromHandle(IntPtr) returns null in one hooked process and returns valid object of "Form"? in another hooked process?

So, fail-safe code would be:

    if (w == nullptr)
        d->Show();
    else
        d->Show(w);