【问题标题】:Centering a child window of WinForms when parent is of WPF当父级是 WPF 时,将 WinForms 的子窗口居中
【发布时间】:2017-02-22 13:33:47
【问题描述】:

我知道设置子窗口属性以在 WinForms 和 WPF 中显示。这可以通过根据 WinForm/WPF 设置父/所有者来完成。

但最近,我遇到了一种情况,我需要将子窗口设置为父窗口的中心,其中子窗口属于 WinForms,而父窗口属于 WPF。

我试过了,

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

这显然行不通,而且

window.StartPosition = FormStartPosition.CenterParent;

之后,

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

同样,不会工作。

关于如何实现这一点的任何建议?

【问题讨论】:

  • 你的第二个例子:“window.StartPosition = FormStartPosition.CenterParent;”为我工作。不过,我无法解释原因。

标签: c# wpf winforms


【解决方案1】:

我认为没有内置的方法来做你想做的事,但计算价值并不太难。这是一个简单的计算,将子节点的中心设置为父节点的中心。

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();

注意:它不包括父级或子级的窗口镶边, 所以它可能会在垂直方向上稍微偏离中心。

【讨论】:

  • 那就没有别的办法了。
猜你喜欢
  • 2014-11-03
  • 2017-09-20
  • 2015-02-12
  • 2011-10-19
  • 1970-01-01
  • 1970-01-01
  • 2017-08-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多