[英]Centering a child window of WinForms when parent is of WPF
I know setting up child window property for displaying in WinForms and WPF. 我知道设置子窗口属性以在WinForms和WPF中显示。 This can be done by setting up the parent / owner depending on WinForm/ WPF.
这可以通过根据WinForm / WPF设置父/所有者来完成。
But recently, I came across a situation where I need to setup the child window to center of parent, where Child is of WinForms and parent is of WPF. 但是最近,我遇到了一种情况,我需要将子窗口设置为父窗口的中心,其中子窗口为WinForms,父窗口为WPF。
I tried with, 我尝试过
newForm window = new newForm;
window.Owner = this;
Which would obviously won't work, and 显然不起作用,并且
window.StartPosition = FormStartPosition.CenterParent;
after, 后,
newForm window = new newForm;
window.MdiParent = this;
Also, won't work. 另外,也行不通。
Any suggestions on how can I possibly achieve this? 关于如何实现这一目标的任何建议?
I don't think there is a built in way to do what you want, but calculating the value isn't overly difficult. 我认为没有内置的方法可以执行您想要的操作,但是计算值并不是很困难。 Here is a simple calculation that sets the center of the child equal to the center of the parent.
这是一个简单的计算,将子项的中心设置为与父项的中心相等。
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();
Note: It does not include the window chrome for either the parent or the child, so it may be slightly off center vertically. 注意:它不包含父母或孩子的窗口镶边,因此它可能在垂直方向上稍微偏离中心。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.