Dot NET
Dot NET

Reputation: 4907

How to drag a picturebox control

I've got a class called 'MusicNote' which inherits from 'PictureBox'. I'm trying to make it drag vertically when the user clicks on it and moves the mouse up/down. I've pasted the code below, which works. The problem is that it only works the first time - i.e. the user drags it and it's placed in the new position as it's supposed to. However, when I click it again and drag - it disappears. Any ideas?

Upvotes: 2

Views: 156

Answers (2)

Maheep
Maheep

Reputation: 5605

Problem is with the MouseUp event handler. In that event you will have to unsubscribe to MouseMove event handler.

    public void MusicNote_MouseUp(object sender, MouseEventArgs e)
    {
        isDragging = false;
        this.MouseMove -= new MouseEventHandler(OnDrag);
    }

Multiple subscription to same event is causing your controls top value to be negative.

Upvotes: 2

Jamie Hutton
Jamie Hutton

Reputation: 260

It seems the currentX and currentY variables are not updated in OnDrag

 public void MusicNote_MouseUp(object sender, MouseEventArgs e)
        {
            isDragging = false;

            currentX  = e.X;
            currentY  = e.Y;
        }

Upvotes: 0

Related Questions