如何使面板位于窗体中央?

28
如何使表单面板居中,即使表单大小发生变化。 使用 C# Windows 应用程序。

您想让面板随窗体一起增长和缩小吗?还是保持原始大小? - Binary Worrier
@Binary Worrier,它应该保持原始大小。但是根据表单的大小应该居中显示。 - Anuya
3个回答

47

使用设计器将面板置于表单中心,然后清除Anchor属性,这样它就不会锚定到任何边缘。这将使其在表单调整大小时保持居中,而不会调整面板本身的大小。

如果由于某种原因需要在代码中定位面板(例如,取决于表单加载期间发生的事情),可以像这样操作:

// code for initializing the panel and setting 
// its size goes here

_thePanel.Location = new Point(
    this.ClientSize.Width / 2 - _thePanel.Size.Width / 2,
    this.ClientSize.Height / 2 - _thePanel.Size.Height / 2);
_thePanel.Anchor = AnchorStyles.None;

我想那应该适用于大多数情况。


我的面板里有很多控件。这个应用程序将在许多分辨率不同的系统中运行。因此,在这种情况下,面板的位置对于不同的系统是不同的。 - Anuya
1
太棒了!我从来不知道你可以完全删除锚点。 - Jason L.

6

将其Anchor属性设置为None:

this.panel1.Anchor = System.Windows.Forms.AnchorStyles.None;

1
Private Sub Panel1_Paint(sender As Object, e As PaintEventArgs) Handles Panel1.Paint
    Panel1.Location = New Point(ClientSize.Width / 2 - Panel1.Size.Width / 2, ClientSize.Height / 2 - Panel1.Size.Height / 2)
    Panel1.Anchor = AnchorStyles.None
End Sub

2
请注意,仅提供代码答案是不被鼓励的。请始终在其周围提供一些解释! - GhostCat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接