C# 如何拖放动态创建的矩形

C# How to drag and drop dynamically created rectangles

UserControl 中,我可以通过单击添加 Rectangles。这些矩形保存在一个列表中。现在我想让用户能够移动那些绘制的 Rectangles 。 首先,我尝试将 MouseDownMouseMoveMouseUp 事件添加到 Rectangle,但这不起作用,因为 Drawing Rectangle 是一个 Struct 而不是一个控件。我已经做了一个 Testproject 并完成了移动我放在 UserControl 中的按钮。我尝试使用从 Drag and Drop Function with Drawing Rectangle C# .net - Forms 获得的代码,但此示例与矩形无关。它是关于控件的,我不知道如何将这个想法用于矩形,因为

rectangle.MouseDown += delegate(object sender, MouseEventArgs e)
{
  //do something
}

不起作用。任何关于如何拖放动态添加的矩形的想法?

您应该将 MouseDown 事件添加到 UserControl。然后遍历列表并创建一个方法来查看坐标是否在 Rectangle 内。如果是,则钩住并移动它。

所以你应该添加一个 bool 值,在 MouseDown 事件中设置为 true 并在 MouseUp 事件中设置为 false事件。然后在 MouseMove 事件中,检查 mouseDown 值是否为 true。如果是,并且找到 Rectangle,请移动它的位置。