2009-02-04 21 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窗口...