2017-02-22 100 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