我们如何获得相对于窗体的位置?

时间:2010-02-24 13:42:47

标签: c# .net drag-and-drop

我正在实现一个可以在面板中拖放图像的应用程序,所以我想确保图像放在面板中,并且在删除时可以看到整个图像。在这种情况下,我想要我在执行拖放事件时获取当前光标位置。那么如何才能获得与面板相关的光标位置? 这是面板拖放事件的方法。

private void panel1_DragDrop(object sender, DragEventArgs e)
{
    Control c = e.Data.GetData(e.Data.GetFormats()[0]) as Control;

    if (c != null)
    {
        if (e.X < 429 && e.X > 0 && e.Y<430 && e.Y>0)
        {
            c.Location = this.panel1.PointToClient((new Point(e.X, e.Y)));**

            this.panel1.Controls.Add(c);
        }
    }  
}

1 个答案:

答案 0 :(得分:3)

您可以使用Cursor.Position获取光标坐标,这可以获得屏幕坐标。然后,您可以将这些传递到PointToClient(Point p)

Point screenCoords = Cursor.Position;
Point controlRelatedCoords = this.panel1.PointToClient(screenCoords);

尽管如此,我相当确定DragEventArgs.XDragEventArgs.Y已经是屏幕坐标。你的问题可能在于

 if (e.X < 429 && e.X > 0 && e.Y<430 && e.Y>0)

看起来它会检查Panel坐标,而e.Xe.Y是该点的屏幕坐标。相反,在检查边界之前将其转换为面板坐标:

 Point screenCoords = Cursor.Position;
 Point controlRelatedCoords = this.panel1.PointToClient(screenCoords);
 if (controlRelatedCoords.X < 429 && controlRelatedCoords.X > 0 && 
     controlRelatedCoords.Y < 430 && controlRelatedCoords.Y > 0)
 {

 }
相关问题