How do I keep a label centered in WinForms?

后端 未结 7 1029
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-07 11:21

In WinForms I am using a Label to display different messages like success, failure, etc.

I\'d like to center that label in the center form.

相关标签:
7条回答
  • 2020-12-07 11:59

    You will achive it with setting property Anchor: None.

    0 讨论(0)
  • 2020-12-07 12:00

    You could try out the following code snippet:

    private Point CenterOfMenuPanel<T>(T control, int height=0) where T:Control {
        Point center = new Point( 
            MenuPanel.Size.Width / 2 - control.Width * 2,
            height != 0 ? height : MenuPanel.Size.Height / 2 - control.Height / 2);
    
        return center;
    }
    

    It's Really Center

    enter image description here

    0 讨论(0)
  • 2020-12-07 12:01

    If you don't want to dock label in whole available area, just set SizeChanged event instead of TextChanged. Changing each letter will change the width property of label as well as its text when autosize property set to True. So, by the way you can use any formula to keep label centered in form.

    private void lblReport_SizeChanged(object sender, EventArgs e)
    {
        lblReport.Left = (this.ClientSize.Width - lblReport.Size.Width) / 2;
    }
    
    0 讨论(0)
  • 2020-12-07 12:03

    I wanted to do something similar, but on a form with a background image, I found that when the text in the label changed the repaints were obvious with this method, so I did the following: * Set the label AutoSize to true and TextAlign to MiddleCenter

    Then, each time the text changed (mine was done using a timer) I called the following method:

        private Point GetPosition()
        {
            int y = (this.Height / 2) - (label1.Height / 2);
            int x = (this.Width / 2) - (label1.Width / 2);
            return new Point(x, y);
        }
    

    And set the label's Location property to this return value. This ensured that the label was always in the center of the form when the text changed and the repaints for a full-screen form weren't obvious.

    0 讨论(0)
  • 2020-12-07 12:07

    Set Label's AutoSize property to False, TextAlign property to MiddleCenter and Dock property to Fill.

    0 讨论(0)
  • 2020-12-07 12:08

    The accepted answer didn't work for me for two reasons:

    1. I had BackColor set so setting AutoSize = false and Dock = Fill causes the background color to fill the whole form
    2. I couldn't have AutoSize set to false anyway because my label text was dynamic

    Instead, I simply used the form's width and the width of the label to calculate the left offset:

    MyLabel.Left = (this.Width - MyLabel.Width) / 2;
    
    0 讨论(0)
提交回复
热议问题