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?
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".
use the CenterToScreen() Method in the constructor of the form class.
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:
- The Owner property of the form.
- The HWND owner of the form.
- 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)
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With