gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:18:21 27 4
gpt4 key购买 nike

我正在实现一个可以在面板中拖放图像的应用程序,因此我想确保图像放置在面板中并且在拖放时整个图像可见。在那种情况下我想当我进行拖放事件时获取当前光标位置。那么如何获取与面板相关的光标位置呢?这里是面板拖放事件的方法。

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);
}
}
}

最佳答案

您可以使用 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)

这看起来像是在检查面板坐标,而 e.Xe.Y 是此时的屏幕坐标。相反,thansform it into panel coords before checking against bounds :

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

}

关于c# - 我们如何获得相对于窗体的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2326363/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com