Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come CenterToScreen method centers the form on the screen where the cursor is, not the screen with the focused app?

I am using Visual Studio 2010, C# .NET 4, WinForms. My PC has 2 monitors.

When I call the CenterToScreen method of a form, the form centers itself on whichever screen the cursor is on. Does anyone know why?

like image 781
Welton v3.61 Avatar asked Jul 26 '11 22:07

Welton v3.61


People also ask

How do you center a form on a screen?

To center your form in the application screen, open the form in design view. View the Form Properties. Set the "Auto Center" property to "Yes".

How do you center a window on screen in Winforms development in c3?

use the CenterToScreen() Method in the constructor of the form class.


1 Answers

From the documentation:

Do not call this directly from your code. Instead, set the StartPosition property to CenterScreen.

The CenterToScreen method uses the following priority list to determine the screen used to center the form:

  1. The Owner property of the form.
  2. The HWND owner of the form.
  3. The screen that currently has the mouse cursor.

So, effectively it's used during the initial showing of the form. It's not intended to be used later.

You could write your own like so:

protected void ReallyCenterToScreen()
{
    Screen screen = Screen.FromControl(this);

    Rectangle workingArea = screen.WorkingArea;
    this.Location = new Point() {
        X = Math.Max(workingArea.X, workingArea.X + (workingArea.Width - this.Width) / 2),
        Y = Math.Max(workingArea.Y, workingArea.Y + (workingArea.Height - this.Height) / 2)
    };   
}
like image 92
CodeNaked Avatar answered Oct 26 '22 13:10

CodeNaked