How do I center a window onscreen in C#?

后端 未结 12 2064
情书的邮戳
情书的邮戳 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:40

    In case of multi monitor and If you prefer to center on correct monitor/screen then you might like to try these lines:

    // Save values for future(for example, to center a form on next launch)
    int screen_x = Screen.FromControl(Form).WorkingArea.X;
    int screen_y = Screen.FromControl(Form).WorkingArea.Y;
    
    // Move it and center using correct screen/monitor
    Form.Left = screen_x;
    Form.Top = screen_y;
    Form.Left += (Screen.FromControl(Form).WorkingArea.Width - Form.Width) / 2;
    Form.Top += (Screen.FromControl(Form).WorkingArea.Height - Form.Height) / 2;
    

提交回复
热议问题