1

我正在尝试从 Win32 应用程序的子窗口调用 WPF 对话框,并且能够使用调用窗口的窗口句柄 (HWND) 来实现这一点,并将其传递给我使用WindowInteropHelper类设置所有者的 WPF 代码属性为调用窗口的句柄。下面的代码片段显示了我设置 Owner 属性的 WPF 代码。

    public void ShowModal(IntPtr ownerWindow)
    {            
        WindowInteropHelper helper = new WindowInteropHelper(this);
        helper.Owner = ownerWindow;
        this.ShowDialog();
    }

我正在使用 Windows 函数获取调用对话框的 HWND,如下所示:

HWND handle = GetTopWindow(GetActiveWindow());

虽然这在功能上按预期工作(WPF 对话框作为模式对话框调用),但它在屏幕的左上角被调用。我什至WindowStartupLocation="CenterOwner"在 XAML 代码中设置了该属性。当从 WPF 窗口调用时,它工作得非常好,但在涉及 Win32 窗口时却不行。我想我在这里的 WPF-Win32 互操作中遗漏了一些东西,尽管在我看来问题出在从 GetTopWindow(GetActiveWindow()) 检索的 HWND 上。

更新:我将上面的代码替换为将调用窗口的 HWND 替换为下面的代码,现在 WPF 对话框总是在屏幕中心调用,而不管调用它的窗口的位置。

            HWND hWnd = GetActiveWindow();
            if (hWnd != NULL)
            {
                hWnd = FindWindowEx(hWnd, NULL, "Window1", NULL);
                if (hWnd != NULL)
                {
                    hWnd = FindWindowEx(hWnd, NULL, "Window2", NULL);
                }
            }

这里 Window2 是调用 WPF 对话框的窗口。

4

1 回答 1

-1

在您的 ShowModal() 中,您可以尝试:

this.Owner = App.MainWindow;
于 2014-06-10T06:03:25.787 回答