我使用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。有什么想法吗?
发布于 2015-05-28 15:49:11
将Ron的评论转化为一个答案:
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);
}
}
https://stackoverflow.com/questions/30509587
复制相似问题