2014-01-20 51 views
1

我有主窗口,它被設置爲最大化負載。但是,當我Un-Maximize窗口或雙擊窗口的標題欄。它隨機被放置在屏幕上,但不是ScreenCenter在最大化狀態下的CenterScreen窗口,在StateChanged上

有什麼辦法,我可以在ScreenCenter放置窗口時未最大化

我試圖在希望下面的代碼,但沒有工作

private void InfoWindow_OnStateChanged(object sender, EventArgs e) 
{ 
    var window = sender as Window; 
    if(window != null && window.WindowState == WindowState.Normal) 
     WindowStartupLocation = WindowStartupLocation.CenterScreen; 
} 

回答

1

由於WPF不提供直接的這個工作方法,你需要做這樣的事情:

var workingArea = System.Windows.SystemParameters.WorkArea; 
this.Left = (workingArea.Width - this.Width)/2 + workingArea.Left; 
this.Top = (workingArea.Height - this.Height)/2 + workingArea.Top; 
+0

這是winforms –

+0

@ K.B,感謝您的支持。讓我編輯。 –

+1

謝謝它完成了這項工作:) – ADi

1

您可以使用此方法來設置窗口的位置,你的屏幕的中心。

private void CenterWindowOnScreen() 
    { 
     double screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth; 
     double screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight; 
     double windowWidth = this.Width; 
     double windowHeight = this.Height; 
     this.Left = (screenWidth/2) - (windowWidth/2); 
     this.Top = (screenHeight/2) - (windowHeight/2); 
    } 

private void InfoWindow_OnStateChanged(object sender, EventArgs e) 
{ 
    var window = sender as Window; 
    if(window != null && window.WindowState == WindowState.Normal) 
     CenterWindowOnScreen(); 
} 
+0

爲你的時間,你的解決方案也工作 – ADi

相關問題