Search code examples
c#winformsoverridingpicturebox

Override OnMouseMoveEvent after creating own cs file


My movable_picturebox.cs file contains:

public class movable_picturebox : PictureBox
{

    public movable_picturebox(IContainer container)
    {
        container.Add(this);
    }

    Point point;

    protected override void OnMouseDown(MouseEventArgs e)
    {
        point = e.Location;
        base.OnMouseDown(e);
    }

    protected override void OnMouseMove(MouseEventArgs e)
    {

        if(e.Button == MouseButtons.Left)
        {
            this.Left += e.X - point.X;
            this.Top += e.Y - point.Y;
        }
    }

}

And now when I add in winforms my moveable_picturebox element I can move it by holding down mouse wherever I want.

What do I need to do to stop this event? For example: I start program, I move my picture box in specific position, And I need to stop this event, to be not able move this picturebox. I need to override this event again but, how can I do that? And code what should contains?


Solution

  • Instead of overriding the method again, just add another condition check in the existing method. Have a boolean where you set whether or not you canMovePictureBox, and change function to

    protected override void OnMouseMove(MouseEventArgs e)
    {
        if(e.Button == MouseButtons.Left && canMovePictureBox)
        {
            this.Left += e.X - point.X;
            this.Top += e.Y - point.Y;
        }
    }