开发者

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

开发者 https://www.devze.com 2023-03-22 22:16 出处:网络
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 anyo开发者_

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 anyo开发者_Python百科ne know why?


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)
    };   
}


Its by design: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.centertoscreen.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消