简体   繁体   中英

Centering a child window of WinForms when parent is of WPF

I know setting up child window property for displaying in WinForms and WPF. This can be done by setting up the parent / owner depending on 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM