Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...