我正在学习C#并选择了一个项目来编写一个简单的颜色选择器控件;但是,自从我上次编写代码以来,事情发生了很大变化,我已经解决了这个问题。
我在我的控制中使用Mousedown事件将鼠标坐标作为Point - 这工作正常并且返回我期望的 - 鼠标坐标相对于我的控件;然而,当我尝试对控制位置进行检查时,我返回一个值作为Point,显示我的控件相对于窗体的位置,在某些情况下鼠标坐标将超出边界,因为它们的值将小于控件IE的相对起始位置我在控件中的像素1,1处单击 - 鼠标位置为1,1但由于控件位于相对于表格的9,9,因此鼠标的位置小于边界控制 - 我完全不知道如何解决这个问题,我一直试图用PointToClient和PointToScreen来解决它无济于事,因为他们似乎想出了古怪的价值观,有人可以帮助我,这让我疯了。
答案 0 :(得分:0)
我已经设法解决了这个问题,所以我想我会发布答案,它可以帮助别人。我在获取相对于相同像素原点的Point值时遇到了问题:这对它进行了排序。
private void ColourPicker_MouseDown(object sender, MouseEventArgs e)
{ // Probably being paranoid but I am worried about scaling issues, this.Location
// would return the same result as this mess but may not handle
// scaling <I haven't checked>
Point ControlCoord = this.PointToClient(this.PointToScreen(this.Location));
int ControlXStartPosition = ControlCoord.X;
int ControlYStartPosition = ControlCoord.Y;
int ControlXCalculatedWidth = ((RectangleColumnsCount + 1) * WidthPerBlock ) + ControlXStartPosition;
int ControlYCalculatedHeight = ((RectangleRowsCount + 1) * HeightPerBlock) + ControlYStartPosition;
// Ensure that the mouse coordinates are comparible to the control coordinates for boundry checks.
Point ControlRelitiveMouseCoord = this.ParentForm.PointToClient(this.PointToScreen(e.Location));
int ControlRelitiveMouseXcoord = ControlRelitiveMouseCoord.X;
int ControlRelitiveMouseYcoord = ControlRelitiveMouseCoord.Y;
// Zero Relitive coordinates are used for caluculating the selected block location
int ZeroRelitiveXMouseCoord = e.X;
int ZeroRelitiveYMouseCoord = e.Y;
// Ensure we are in the CALCULATED boundries of the control as the control maybe bigger than the painted area on
// the design time form and we don't want to use unpaited area in our calculations.
if((ControlRelitiveMouseXcoord > ControlXStartPosition) && (ControlRelitiveMouseXcoord < ControlXCalculatedWidth))
{
if((ControlRelitiveMouseYcoord > ControlYStartPosition) && (ControlRelitiveMouseYcoord < ControlYCalculatedHeight))
{
SetEvaluatedColourFromPosition(ZeroRelitiveXMouseCoord, ZeroRelitiveYMouseCoord);
}
}
}