Search code examples
c#playing-cards

problem with moving picturebox


I am programming a cards game, when i was doing the visual part i had a problem with moving the card within a panel from one place to another, the image keeps blinks and moves every where when i try to move it.

This is my code.....

public partial class Form1 : Form
{
    bool clicked = false;
    public Form1()
    {
        InitializeComponent();
        pictureBox1.ImageLocation = @"c:\kingHearts.png";
        pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;

    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        clicked = true;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (clicked)
            pictureBox1.Location = e.Location;
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        clicked = false;

    }
}

So what is wrong, anyone can help plz....


Solution

  • A very typical pattern for moving by click-and-drag for ui objects at runtime, and which will work when the control is on a form, or in a container like a Panel :

    private bool pb_mouseIsDown;
    private int oX;
    private int oY;
    
    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        pb_mouseIsDown = true;
        oX = e.X;
        oY = e.Y;
    }
    
    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        pb_mouseIsDown = false;
    }
    
    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (pb_mouseIsDown)
        {
            pictureBox1.Left += e.X - oX;
            pictureBox1.Top += e.Y - oY;
        }
    }
    

    Note : ...at Design Time : if you define the event handlers for MouseUp, MouseDown, and MouseMove while the control is "on" a Form (the parent of the control is the Form), and then cut and paste it into a container, like a Panel : you'll have re-establish the binding/linkage between the control and the MouseDown, MouseUp, and MouseMove events in the IDE for it to work.