【问题标题】:Open Window on the Same Monitor as MainWindow在与 MainWindow 相同的监视器上打开窗口
【发布时间】:2017-02-08 08:29:58
【问题描述】:

我已经看到很多关于类似问题的问题,但我还没有找到一个足够具体到我的问题来找到答案的问题。

我允许用户移动我的程序的 MainWindow,如果他们有的话,可以移动到另一台监视器上。当他们在 MainWindow 上单击添加内容时,会创建一个新窗口,以便他们可以填写表格。

问题是这个新窗口将在操作系统的主屏幕上启动,而不是在 MainWindow 当前所在的屏幕上启动。

我看过这个问题; How to make a dialog(view) open up on the same monitor as the main window 并看到在这种情况下将所有者设置为 MainWindow 有效。所以我加了

Owner = Application.Current.MainWindow;

进入Window_Loaded 方法新建Window。这确实会在与 MainWindow 相同的屏幕上加载 Window,但随后会崩溃,说明 Cannot set Owner property after Dialog is shown.

我很自然地将 Owner 属性的设置移到了新窗口显示之前,所以它看起来像这样;

contractAddwindow.Owner = Application.Current.MainWindow; contractAddwindow.ShowDialog();

然而这与以前有同样的问题,contractAddWindow 在主屏幕上启动。

所以我的问题是,如何强制新窗口加载到与 MainWindow 而不是主屏幕相同的监视器上?

【问题讨论】:

    标签: c# wpf window


    【解决方案1】:

    你可以使用WindowStartupLocation:

    来自 XAML:

    WindowStartupLocation="CenterOwner"
    

    来自代码:

    WindowStartupLocation = WindowStartupLocation.CenterOwner;
    

    【讨论】:

    • 还记得在设置之前先设置 Owner。
    【解决方案2】:

    @EDIT:在使用这个答案之前,请考虑尝试 Nawed 的答案(见下文)。他的要简单得多。

    试试这个方法:

    using System.Windows;
    using System.Windows.Forms; // Reference System.Drawing
    
    [...]
    
    public void SetWindowScreen(Window window, Screen screen)
    {
        if (screen != null)
        {
            if (!window.IsLoaded)
            {
                window.WindowStartupLocation = WindowStartupLocation.Manual;
            }
    
            var workingArea = screen.WorkingArea;
            window.Left = workingArea.Left;
            window.Top = workingArea.Top;
        }
    }
    
    public Screen GetWindowScreen(Window window)
    {
        return Screen.FromHandle(new System.Windows.Interop.WindowInteropHelper(window).Handle);
    }
    

    然后,从 Window 的构造函数中这样调用它,您希望在与 MainWindow 相同的监视器上显示:

    SetWindowScreen(this, GetWindowScreen(App.Current.MainWindow));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-11
      • 2014-01-27
      • 2016-04-28
      • 2018-01-02
      • 1970-01-01
      • 2010-11-25
      相关资源
      最近更新 更多