【问题标题】:How do I set an umanaged dialog as the Owner of a WinForm Form?如何将非托管对话框设置为 WinForm 表单的所有者?
【发布时间】:2015-09-23 11:26:36
【问题描述】:

我需要能够获得 WinForm 对话框的 Owner's HWND。在非托管中,我有一个后台线程可以获取前面窗口的 HWND。然后代码调用 ::GetParent(frontHWND) 以查看它是否需要隐藏不同的非模态 MFC 对话框。当 WinForm 对话框是 frontHWND 时,我总是为 GetParent 调用返回 NULL。我也试过 GetOwner 意识到 .Net 试图清理父级和所有者之间的差异。查看带有 Spy++ 的 WinForm 对话框,它还说 WinForm 没有父级或所有者。我通过了

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

上面的代码没有设置 WinForm 的所有者。我尝试从 OnFormShown() 中的 WinForm 代码调用 Win32 SetParent,但锁定了 MFC 应用程序和 WinForm。

有人可以解释如何让我的非托管对话框/应用程序成为托管 winform 的所有者/父级吗?

【问题讨论】:

  • 任何信息都会有所帮助......就像 ShowDialog(IWin32Window) 实际设置的那样。根据此链接link,它应该设置所有者,但是当我使用 Spy++ 时,我看不到。

标签: c# c++ interop winforms-interop


【解决方案1】:

要显示带有 C++ 父级的 C# 表单,我这样做:

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);
}

此代码被放入 C++/CLI 包装 DLL 中。 希望这会有所帮助。

编辑: "w" 必须针对 nullptr 进行测试,因为 Control::FromHandle 可能会失败。看这里: Why Control.FromHandle(IntPtr) returns null in one hooked process and returns valid object of "Form"? in another hooked process?

因此,故障安全代码将是:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    相关资源
    最近更新 更多