How do I keep a label centered in WinForms?

后端 未结 7 1033
爱一瞬间的悲伤
爱一瞬间的悲伤 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 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.

提交回复
热议问题