c# 拖拽图形
时间: 2023-07-26 18:03:44 浏览: 105
要实现在 C# 中拖拽图形,可以通过以下步骤:
1. 在窗体上添加需要拖拽的图形控件,例如 PictureBox。
2. 在控件的 MouseDown 事件中,记录鼠标按下时的坐标和控件的位置。
3. 在控件的 MouseMove 事件中,计算鼠标移动的距离,并根据此距离修改控件的位置。
4. 在控件的 MouseUp 事件中,清除记录的坐标和位置信息。
以下是示例代码:
```
public partial class Form1 : Form
{
private bool isDragging = false;
private int mouseX, mouseY;
private int controlX, controlY;
public Form1()
{
InitializeComponent();
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
isDragging = true;
mouseX = e.X;
mouseY = e.Y;
controlX = pictureBox1.Location.X;
controlY = pictureBox1.Location.Y;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (isDragging)
{
int deltaX = e.X - mouseX;
int deltaY = e.Y - mouseY;
pictureBox1.Location = new Point(controlX + deltaX, controlY + deltaY);
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
isDragging = false;
}
}
```