even though i'm really just copy pasting when it comes to windows forms
The code you posted won't actually do anything by itself!
To work, the MouseDown() and MouseMove() events of the control have to be wired up to those methods:
- Select the control on the form (pictureBox1).
- In the Properties Pane (bottom right by default), click the "Lightning Bolt" icon to get a list of the events for that control.
- Find the
MouseDown
entry and change the dropdown to the right of it topictureBox1_MouseDown
. - Find the
MouseMove
entry and change the dropdown to the right of it topictureBox1_MouseMove
.
Now run it and drag the pictureBox1 around.
EDIT: Here is how to make the code work for multiple controls, as outlined in my comment below.
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;
}