【问题标题】:Show Dialog box at center of its parent在其父项的中心显示对话框
【发布时间】:2023-03-11 22:05:01
【问题描述】:

在其父窗体的中心显示一个对话框是一团糟。这是一种显示对话框的方法。

我将其父级定位到中心,但无法将 DialogBox 居中

private void OpenForm(Object point, Object height, Object width)
{
    FormLoading frm = new FormLoading();
    Point temp = (Point)point;
    Point location = new Point(temp.X + (int)((int)width) / 2, 
                               temp.Y + (int)((int)height) / 2);
    frm.Location = location;
    frm.ShowDialog();
}

private void btnView_Click(object sender, EventArgs e)
{
    try
    {                    
        ThreadStart starter= delegate { OpenForm(currentScreenLocation, 
                                                 this.Height, this.Width); };
        Thread t = new Thread(starter);
        t.Start();
        ////// Some functionality here...
        t.Abort();
    }
    catch (Exception)
    {
    }
}

【问题讨论】:

  • 我也会小心多线程。控件的属性(至少是那些处理用户界面的)只能从创建它们的线程中更改。我在这里看不到更大的图景,所以我不知道您为什么要在其自己的线程中创建每个表单,但请记住这一点。

标签: c# winforms .net-4.0 positioning center


【解决方案1】:

您可能需要检查Form.StartPosition 属性。

http://msdn.microsoft.com/en-us/library/system.windows.forms.form.startposition.aspx

类似的东西:

private void OpenForm(Form parent)
{
    FormLoading frm = new FormLoading();
    frm.Parent = parent;
    frm.StartPosition = FormStartPosition.CenterParent;
    frm.ShowDialog();
}

这当然需要设置表单的父级。

【讨论】:

  • frm.StartPosition = FormStartPosition.Manual; frm.Location = 位置;我使用它并为我工作:)
  • 将其设置为 FormStartPosition.CenterParent 为您计算。但我想如果你打算做比居中更复杂的事情,你会想要保留你的代码。很高兴您解决了您的问题。
  • FormStartPosition.CenterParent 对我不起作用。我只是想把它放在中心。但是您提供的链接对我来说是关键。谢谢你
  • frm.Parent = parent; 不起作用,但删除那行代码仍然可以正常工作.. 父事物给出了无法修复的顶级错误。 Top-level control cannot be added to a control
  • 如果您收到“无法添加顶级控件...”异常,请尝试设置所有者:frm.Owner = parent;
【解决方案2】:

【讨论】:

    【解决方案3】:

    如果你正在制作一个自定义的 MessageBox,你可以简单地说:

    CenterToParent();
    

    在您的自定义 MessageBox formload() 方法中。

    【讨论】:

      【解决方案4】:

      另外,如果你想设置任意位置,你可以使用这个

      FormLoading frm = new FormLoading();
      Point location = new Point(300, 400);
      frm.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
      frm.Location = location;
      frm.ShowDialog();
      

      【讨论】:

        【解决方案5】:
        NewForm.Show();
        
        NewForm.Top = (this.Top + (this.Height / 2)) - NewForm.Height / 2;
        NewForm.Left = (this.Left + (this.Width / 2)) - NewForm.Width / 2;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-10-14
          • 2019-04-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-11
          • 2012-11-08
          • 1970-01-01
          相关资源
          最近更新 更多