2009-02-04 22 views

回答

14

WPF不包含方便的System.Windows.Forms。 Screen class,但仍然可以使用它的属性在WinForms应用程序中完成您的任务。

假设指的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窗口的“所有者”属性。

1

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

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

6

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

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

dialogWindow.ShowDialog(); 

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

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窗口...