显示带有WPF,Winforms和双显示器的窗口

时间:2009-02-04 17:23:51

标签: c# wpf winforms multiple-monitors

我有一个2个监视器和一个启动WPF窗口的WinForm应用程序。我想获得WinForm所在的屏幕,并在同一屏幕上显示WPF窗口。我怎么能这样做?

4 个答案:

答案 0 :(得分:14)

WPF不包括方便的System.Windows.Forms。屏幕类,但您仍然可以使用其属性在WinForms应用程序中完成任务。

假设 this 表示WinForms窗口, _wpfWindow 是引用下面示例中WPF窗口的已定义变量(这将在您设置为打开的任何代码处理程序中) WPF窗口,就像一些Button.Click处理程序):

Screen screen = Screen.FromControl(this);
_wpfWindow.StartupLocation = System.Windows.WindowStartupLocation.Manual;
_wpfWindow.Top = screen.Bounds.Top;
_wpfWindow.Left = screen.Bounds.Left;
_wpfWindow.Show();

上面的代码将在包含WinForms窗口的屏幕左上角实例化WPF窗口。如果您希望将它放在屏幕中间的其他位置或WinForms窗口右下方的“级联”样式中,我会将数学留给您。

另一种在屏幕中间获取WPF窗口的方法是简单地使用

_wpfWIndow.StartupLocation = System.Windows.WindowStartupLocation.CenterScreen

然而,这并不是那么灵活,因为它使用鼠标的位置来确定哪个屏幕显示WPF窗口(显然,如果用户移动它,鼠标可以在WinForms应用程序的不同屏幕上快点,或者您使用默认按钮,或其他)。

编辑:Here's a link to an SDK document关于使用InterOp让WPF窗口居中于非WPF窗口。它基本上完成了我在描述数学方面所描述的内容,但正确地允许您使用Window的HWND设置WPF窗口的“Owner”属性。

答案 1 :(得分:6)

这是最简单的方法(使用WindowStartupLocation.CenterOwner)。

MyDialogWindow dialogWindow = new MyDialogWindow();
dialogWindow.Owner = this;
dialogWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner;

dialogWindow.ShowDialog();

无需互操作或设置窗口坐标:)

答案 2 :(得分:3)

另一种方法是:

WindowInteropHelper helper = new WindowInteropHelper(this);

this.StartupLocation = System.Windows.WindowStartupLocation.Manual;
this.Left = System.Windows.Forms.Screen.FromHandle(helper.Handle).Bounds.Left;
this.Top = System.Windows.Forms.Screen.FromHandle(helper.Handle).Bounds.Top;

这=你的WPF窗口......

答案 3 :(得分:1)

您应该能够使用System.Windows.Forms.Screen [1],并使用FromControl方法获取表单的屏幕信息。然后,您可以使用它来根据您尝试找到它的屏幕定位WPF窗口(顶部,左侧)。

[1]如果你不加载WinForms dll,你也可以使用win32 MonitorFromRect等。但是,由于您已经获得了winforms API,因此您不会支付任何内存/性能。

相关问题