How to center the shape after programmatically switching screens

Given Form , I want to center the form after switching screens. How can I complete the task?

  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
source share
3 answers

One not-so-easy way to complete a 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 ); } 
+7
source

You need to consider the offset of the monitor before setting the position, but other than that, it should be pretty simple.

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

But Form.CenterToScreen () should work fine, but apparently Microsoft doesn't recommend using it? I do not know why.

+1
source

What if, instead of all these calculations, you simply use Form.CenterToScreen

 this.CenterToScreen(); 
+1
source

Source: https://habr.com/ru/post/1442386/


All Articles