开发者

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, MouseEvent开发者_Go百科Args 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....


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.


e.Location returns the location of the mouse relative to the PictureBox.
You need to write PointToClient(pictureBox1.PointToScreen(e.Location)) to get the location relative to the form.


To the blinking problem, you can set this.DoubleBuffered to true.

But moving PictureBox or another Control is inefficient, better would be to write drawing code into pictureBox1.Paint event or use something faster like the WPF, DirectX or OpenGL.

I don't know which effects do you want to achieve, if everything is static and you don't have big moving parts, then current solution is good enough.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜