【问题标题】:Modal WPF dialog does not invoke at center of the invoking window模态 WPF 对话框不会在调用窗口的中心调用
【发布时间】:2014-06-10 05:52:13
【问题描述】:

我正在尝试从 Win32 应用程序的子窗口调用 WPF 对话框,并且能够使用调用窗口的窗口句柄 (HWND) 实现此目的,并将其传递给我使用 @987654321 的 WPF 代码@class 将 Owner 属性设置为调用窗口的句柄。下面的代码 sn-p 显示了我设置 Owner 属性的 WPF 代码。

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

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

HWND handle = GetTopWindow(GetActiveWindow());

虽然这在功能上按预期工作(WPF 对话框作为模式对话框调用),但它在屏幕的左上角被调用。我什至在 XAML 代码中设置了 WindowStartupLocation="CenterOwner" 属性。当从 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 对话框的窗口。

【问题讨论】:

    标签: c# wpf winapi window window-handles


    【解决方案1】:

    在你的 ShowModal() 中你能试试吗:

    this.Owner = App.MainWindow;
    

    【讨论】:

    • 我不认为我可以设置 App.MainWindow 因为 WPF 对话框是一个独立的可重复使用的对话框,我试图从 Win32 应用程序的子窗口调用它。我应该在我最初的帖子中提到它。
    猜你喜欢
    • 1970-01-01
    • 2017-08-17
    • 2015-04-30
    • 2014-01-05
    • 2020-01-27
    • 2020-12-26
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多