PointToScreen多个监控器

时间:2015-05-28 14:32:34

标签: c# multiple-monitors

我正在使用PointToScreen来确定弹出窗口的位置,以便它除了用于弹出窗口的按钮之外。 但是,该按钮位于工具栏上,因此用户可以移动弹出窗口。

弹出窗口的位置效果很好,但如果用户在象限上,我想将弹出窗口移到底部(而不是下方)或左侧(而不是右侧)。

问题是在多显示器设置中,PointToScreen传送到主屏幕控制的位置,所以如果我还有另一个屏幕,那么X可能是负片等等。

Point location = new Point(buttonItem.ButtonBounds.X, buttonItem.ButtonBounds.Y);
location = toolBar.PointToScreen(location);
int screenHeight = Screen.FromControl(this).Bounds.Height;
int screenWidth = Screen.FromControl(this).Bounds.Width;
PopupWindow.Quadrant quad = location.Y < screenHeight / 2
    ? PopupWindow.Quadrant.Top
    : PopupWindow.Quadrant.Bottom;
quad |= location.X < screenWidth / 2
    ? PopupWindow.Quadrant.Left
    : PopupWindow.Quadrant.Right;

// ...
//Do stuff to adjust the position of the pop-up based on the quadrant

现在,我希望我可以在没有做一些丑陋的DllImport的情况下获得相对于它所在屏幕的按钮位置。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

将Ron Beyer的评论转化为答案:

static class ControlExtensions
{
    ///<summary>
    /// Returns the position of the point in screen coordinates of that control instead
    /// of the main-screen coordinates
    ///</summary>
    public static Point PointToCurrentScreen(this Control self, Point location)
    {
        var screenBounds = Screen.FromControl(self).Bounds;
        var globalCoordinates = self.PointToScreen(location);
        return new Point(globalCoordinates.X - screenBounds.X, globalCoordinates.Y - screenBounds.Y);
    }
}