4

鉴于Form我想在切换屏幕后将表单居中。我怎样才能完成任务?

 internal static void SetFormToBiggestMonitor(Form form, bool center = true)
    {
        Screen biggestScreen = FindBiggestMonitor();//assume this works
        form.Location = biggestScreen.Bounds.Location;

        if (center)
        {
            form.StartPosition = FormStartPosition.CenterScreen;
        }
    }
4

3 回答 3

7

One not so loopy way to accomplish the task...

    private static Point CenterForm(Form form, Screen screen)
    {
        return new Point(
                         screen.Bounds.Location.X + (screen.WorkingArea.Width - form.Width) / 2,
                         screen.Bounds.Location.Y + (screen.WorkingArea.Height - form.Height) / 2
                         );
    }
于 2012-10-26T18:58:54.410 回答
1

在设置位置之前,您需要考虑监视器的偏移量,但除此之外,它应该相当简单。

if (center)
{
      form.Location = new Point
      (
         biggestScreen.WorkingArea.X + ((biggestScreen.WorkingArea.Width + form.Width)/2),
         biggestScreen.WorkingArea.Y + ((biggestScreen.WorkingArea.Height + form.Height)/2)
      );
}

但是Form.CenterToScreen()应该可以正常工作,但显然微软不建议使用它?不知道为什么。

于 2012-10-26T19:08:41.213 回答
0

如果您只使用Form.CenterToScreen而不是所有这些计算怎么办

this.CenterToScreen();
于 2015-06-10T05:42:58.183 回答