即使我实际上只是复制粘贴,而对于Windows表单
您发布的代码实际上不会单独做任何事情!
要工作,必须将控制的Mousedown()和Mousemove()事件连接到这些方法:
- 选择表单上的控件(Picturebox1)。
- 在“属性窗格”(默认情况下为右下),单击“闪电”图标以获取该控件的事件列表。
- 找出
MouseDown
输入并将其右边的下拉列表更改为pictureBox1_MouseDown
. - 找出
MouseMove
输入并将其右边的下拉列表更改为pictureBox1_MouseMove
.
现在运行它并拖动Picturebox1。
编辑:这是使代码适用于多个控件的方法,如下我的评论中所述。
bool isDragged = false;
Point ptOffset;
private void button1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isDragged = true;
Button btn = (Button)sender;
ptOffset = new Point(btn.Location.X - Cursor.Position.X, btn.Location.Y - Cursor.Position.Y);
}
else
{
isDragged = false;
}
}
private void button1_MouseMove(object sender, MouseEventArgs e)
{
if (isDragged)
{
Point newPoint = Cursor.Position;
newPoint.Offset(ptOffset);
Button btn = (Button)sender;
btn.Location = newPoint;
}
}
private void button1_MouseUp(object sender, MouseEventArgs e)
{
isDragged = false;
}