c# - FormStartPosition.CenterParent 不起作用

标签 c# winforms forms parent-child centering

在下面的代码中,只有第二种方法适用于我 (.NET 4.0)。 FormStartPosition.CenterParent 不会使子窗体在其父窗体上居中。 为什么?

来源:this SO question

using System;
using System.Drawing;
using System.Windows.Forms;

class Program
{
  private static Form f1;

  public static void Main()
  {
    f1 = new Form() { Width = 640, Height = 480 };
    f1.MouseClick += f1_MouseClick; 
    Application.Run(f1);
  }

  static void f1_MouseClick(object sender, MouseEventArgs e)
  {
    Form f2 = new Form() { Width = 400, Height = 300 };
    switch (e.Button)
    {
      case MouseButtons.Left:
      {
        // 1st method
        f2.StartPosition = FormStartPosition.CenterParent;
        break;
      }
      case MouseButtons.Right:
      {
        // 2nd method
        f2.StartPosition = FormStartPosition.Manual;
        f2.Location = new Point(
          f1.Location.X + (f1.Width - f2.Width) / 2, 
          f1.Location.Y + (f1.Height - f2.Height) / 2
        );
        break;
      }
    }
    f2.Show(f1); 
  }
}

最佳答案

这是因为您没有告诉 f2 它的 Parent 是谁。

如果这是一个 MDI 应用程序,则 f2 应该将其 MdiParent 设置为 f1

Form f2 = new Form() { Width = 400, Height = 300 };
f2.StartPosition = FormStartPosition.CenterParent;
f2.MdiParent = f1;
f2.Show();

如果这不是 MDI 应用程序,则需要使用 f1 作为参数调用 ShowDialog 方法。

Form f2 = new Form() { Width = 400, Height = 300 };
f2.StartPosition = FormStartPosition.CenterParent;
f2.ShowDialog(f1);

请注意 CenterParent 无法与 Show 一起正常工作,因为无法设置 Parent,所以如果 ShowDialog 不合适,手动方法是唯一可行的方法。

关于c# - FormStartPosition.CenterParent 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8567058/

相关文章:

c# - 强制 .NET 与应用程序一起使用程序集而不是 GAC

c# - 使用多线程会加速我的 HTML 文件处理应用程序吗?

c# - 为什么这个 ToolStripControlHost 不起作用?

php - 空选择字段表单值留下不需要的空白

c# - 更新 MySQL 会返回受影响的行,但实际上不会更新数据库

c# - 是什么使模板与通用模板不同?

php - 在 PHP 中通过多个表单字段提交操作 HTML 表数据

html - 为什么在我的 GET 请求中有额外的参数 x 和 y?

c# - Microsoft Excel COM 自动化的问题

c# - 如何删除 WinForms DataGrid 中自动生成的空列?