如何使表单面板居中,即使表单大小发生变化。
使用 C# Windows 应用程序。
使用设计器将面板置于表单中心,然后清除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;
我想那应该适用于大多数情况。
将其Anchor属性设置为None:
this.panel1.Anchor = System.Windows.Forms.AnchorStyles.None;
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