用于多监视器的GetWindowRect()的替代方案

本文关键字:方案 GetWindowRect 监视器 用于 | 更新日期: 2023-09-27 18:29:54

我正在尝试将窗体重新定位到控件的右下角。

public void SetAutoLocation()
{
    Rect rect;
    GetWindowRect(referenceControl.Handle, out rect);
    Point targetPoint;
    targetPoint = new Point(rect.left, rect.top + referenceControl.Height);
    if (rect.left + referenceControl.Width - this.Width < 0) //Outside left border
    {
        targetPoint.X = 0;
    }
    else
    {
        targetPoint.X = rect.left - this.Width + referenceControl.Width;
    }
    if (targetPoint.X + this.Width > System.Windows.Forms.SystemInformation.WorkingArea.Right) //Outside right border
    {
        targetPoint.X = System.Windows.Forms.SystemInformation.WorkingArea.Right - this.Width;
    }
    else if (targetPoint.X < 0)
        targetPoint.X = 0;
    if (targetPoint.Y + this.Height > System.Windows.Forms.SystemInformation.WorkingArea.Bottom) //Outside below border
    {
        targetPoint.Y = rect.top - this.Height;
    }
    if (targetPoint.Y < 0)
    {
        targetPoint.Y = 0;
    }
    if (targetPoint.X < 0)
    {
        targetPoint.X = 0;
    }
    this.Location = targetPoint;
    this.Refresh();
}

以上代码在单显示器显示中运行良好。但是,当在双监视器显示中打开父窗体时,该窗体会将自己定位在第一个监视器上,因为GetWindowRect()会返回主显示器内的矩形。

因此,正在寻找一些可能在多显示器上工作的GetWindowRect()的替代方案。

用于多监视器的GetWindowRect()的替代方案

使用Screen类获取控件所在监视器的WorkingArea:

    var screen = Screen.FromControl(referenceControl);
    var area = screen.WorkingArea;
    var rect = referenceControl.RectangleToScreen(
        new Rectangle(0, 0, referenceControl.Width, referenceControl.Height));
    // etc..

请注意RectangleToScreen可以帮助您避免对GetWindowRect()进行微调。

如果您查阅MSDN,它明确指出SystemInformation.WorkingArea只返回主监视器的信息:

WorkingArea始终返回主监视器的工作区域。如果您需要在多显示器环境中的显示器的工作区域,您可以调用Screen.GetWorkingArea.的重载之一