C# 如何在多监视器环境中轻松找到窗体位置的屏幕位置?

C# 如何在多监视器环境中轻松找到窗体位置的屏幕位置?,c#,winforms,multiple-monitors,C#,Winforms,Multiple Monitors,在多监视器环境中运行的C#winform应用程序中(桌面扩展到2或3个监视器),窗体的Location属性表示窗体在扩展桌面上的位置,而不是窗体在物理屏幕上的位置。对于窗体所在的屏幕,是否有一种简单的方法可以在屏幕坐标中找到窗体的位置?因此,如果表单位于第二个或第三个显示的左上角,则位置将为(0,0)///返回表单相对于左上角的位置 ///包含窗体左上角的屏幕,如果 ///表单的左上角不在屏幕上。 公共点?GetLocationWithinScreen(表单) { foreach(屏幕中的屏幕。

在多监视器环境中运行的C#winform应用程序中(桌面扩展到2或3个监视器),窗体的Location属性表示窗体在扩展桌面上的位置,而不是窗体在物理屏幕上的位置。对于窗体所在的屏幕,是否有一种简单的方法可以在屏幕坐标中找到窗体的位置?因此,如果表单位于第二个或第三个显示的左上角,则位置将为(0,0)

///返回表单相对于左上角的位置
///包含窗体左上角的屏幕,如果
///表单的左上角不在屏幕上。
公共点?GetLocationWithinScreen(表单)
{
foreach(屏幕中的屏幕。所有屏幕)
if(screen.Bounds.Contains(form.Location))
返回新点(form.Location.X-screen.Bounds.Left,
form.Location.Y-screen.Bounds.Top);
返回null;
}
/// <summary>Returns the location of the form relative to the top-left corner
/// of the screen that contains the top-left corner of the form, or null if the
/// top-left corner of the form is off-screen.</summary>
public Point? GetLocationWithinScreen(Form form)
{
    foreach (Screen screen in Screen.AllScreens)
        if (screen.Bounds.Contains(form.Location))
            return new Point(form.Location.X - screen.Bounds.Left,
                             form.Location.Y - screen.Bounds.Top);

    return null;
}