You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在VS 2015的Form中精准居中放置Label或Button?

How to Center a Label/Button Horizontally on a Form in VS 2015

Hey there! I totally get how frustrating it can be when you can’t find the right tools to get your controls perfectly aligned in Visual Studio 2015. Let me break down two straightforward ways to center your Label or Button along the X-axis—one for design time (no code needed) and one for runtime (dynamic alignment).

Design Time (Visual Alignment)

If you want to set the position directly in the designer without writing code, use these steps:

  • Select the Label or Button you want to center.
  • Go to the top menu bar, click Format → Align → Horizontally Center in Form. This will instantly snap the control to the horizontal center of your Form.
  • Optional: To make sure the control stays centered if you resize the Form later, set the control’s Anchor property to Top (uncheck Left and Right) in the Properties window. This way, when the Form resizes, the control will keep its horizontal center position while staying fixed to the top.

Runtime (Code-Based Alignment)

If you need the control to center dynamically (e.g., after changing the control’s text or resizing the Form at runtime), use this code approach:

Open your Form’s code-behind file, then add this code to the Load event (and optionally the Resize event to handle window resizing):

private void Form1_Load(object sender, EventArgs e)
{
    CenterControlHorizontally(label1);
    CenterControlHorizontally(button1);
}

private void Form1_Resize(object sender, EventArgs e)
{
    CenterControlHorizontally(label1);
    CenterControlHorizontally(button1);
}

// Helper method to reuse the logic for any control
private void CenterControlHorizontally(Control control)
{
    // Calculate the horizontal center position
    int centerX = (this.ClientSize.Width - control.Width) / 2;
    // Keep the control's current Y position, or set a fixed value if needed
    control.Location = new Point(centerX, control.Location.Y);
}

Quick Notes:

  • Using ClientSize.Width instead of Width ensures we’re using the actual usable area of the Form (excluding the title bar and borders).
  • If your Label has AutoSize set to True, its width will automatically adjust to fit its text, and the code will still calculate the correct center position.

内容的提问来源于stack exchange,提问作者Msorich

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:17:04