c# - 为什么 CenterToScreen 方法会在光标所在的屏幕而不是具有焦点的应用程序的屏幕上使表单居中?

标签 c# winforms .net-4.0

我正在使用 Visual Studio 2010、C# .NET 4、WinForms。我的电脑有 2 个显示器。

当我调用窗体的 CenterToScreen 方法时,窗体会在光标所在的屏幕上居中。有谁知道为什么吗?

最佳答案

来自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.

因此,在表单的初始显示期间有效地使用了它。它不打算以后使用。

你可以这样写你自己的:

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

关于c# - 为什么 CenterToScreen 方法会在光标所在的屏幕而不是具有焦点的应用程序的屏幕上使表单居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6837463/

相关文章:

c# - 通过 EF Core 将 1.3GB CSV 文件导入 sqlite

c# - Xamarin.Forms 和 ElementName 的绑定(bind)

c# - TreeView 通过一些节点移除 CheckBox

c# - 确定按钮上的用户帐户控制

c# - 收听键盘快捷键 (c#)

c# - 如何在 Visual Studio 2010 中将自己的扩展添加到 html/aspx 代码编辑器的上下文菜单中?

c# - 使 asp.Net 应用程序支持浏览器的后退按钮的必须条件是什么?

c# - 获取 WPF Treeview 的 SelectedItem

.net - 如何在没有 Visual Studio 的情况下查看远程 .NET 应用程序中哪个线程发疯

C# 程序集位置解析