2017-02-22 147 views
0

我知道在WinForms和WPF中設置子窗口屬性。這可以通過根據WinForm/WPF設置父/所有者來完成。當父窗口是WPF時居中WinForm的子窗口

但是最近,我遇到了一種情況,我需要將子窗口設置爲父窗口的中心,其中Child是WinForms,父窗口是WPF。

我試着用,

newForm window = new newForm; 
window.Owner = this; 

這顯然是行不通的,而

window.StartPosition = FormStartPosition.CenterParent; 

後,

newForm window = new newForm; 
window.MdiParent = this; 

此外,將無法正常工作。

有關我該如何實現這一目標的任何建議?

回答

0

我不認爲有內置的方式來做你想做的事情,但計算價值不是太困難。這是一個簡單的計算,它將孩子的中心設置爲等於父母的中心。

var form = new Form(); 
//This calculates the relative center of the parent, 
//then converts the resulting point to screen coordinates. 
var relativeCenterParent = new Point(ActualWidth/2, ActualHeight/2); 
var centerParent = this.PointToScreen(relativeCenterParent); 
//This calculates the relative center of the child form. 
var hCenterChild = form.Width/2; 
var vCenterChild = form.Height/2; 
//Now we create a new System.Drawing.Point for the desired location of the 
//child form, subtracting the childs center, so that we end up with the child's 
//center lining up with the parent's center. 
//(Don't get System.Drawing.Point (Windows Forms) confused with System.Windows.Point (WPF).) 
var childLocation = new System.Drawing.Point(
    (int)centerParent.X - hCenterChild, 
    (int)centerParent.Y - vCenterChild); 
//Set the new location. 
form.Location = childLocation; 

//Set the start position to Manual, otherwise the location will be overwritten 
//by the start position calculation. 
form.StartPosition = FormStartPosition.Manual; 

form.ShowDialog(); 

注:不包括窗口鑲邊無論是家長還是孩子, 所以它可能會稍微偏離中心垂直。

+0

那麼沒有其他辦法了。 – Prajwal