How do I center a window onscreen in C#?

后端 未结 12 2065
情书的邮戳
情书的邮戳 2020-12-02 09:05

I need a way to center the current window. So for example, if a user pushes a button, I want the window to center itself onscreen. I know you can use the startposition prope

12条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 09:43

    Might not be completely relevant to the question. But maybe can help someone.

    Center Screen non of the above work for me. Reason was I was adding controls dynamically to the form. Technically when it centered it was correct , based on the form before adding the controls.

    So here was my solution. ( Should work with both scenarios )

    int x = Screen.PrimaryScreen.Bounds.Width - this.PreferredSize.Width;
    int y = Screen.PrimaryScreen.Bounds.Height - this.PreferredSize.Height;
    
    this.Location = new Point(x / 2, y / 2);
    

    So you will notice that I am using "PreferredSize" instead of just using Height / Width. The preferred size will hold the value of the form after adding the controls. Where Height / Width won't.

    Hope this helps someone .

    Cheers

提交回复
热议问题