user2509901
user2509901

Reputation:

Simple button move

I have a card game application, and I want to create a simple animation that will make the button move when it is clicked and dragged.

I have tried:

    bool _Down = false;

    private void button1_MouseDown(object sender, MouseEventArgs e)
    {
        _Down = true;
    }

    private void button1_MouseUp(object sender, MouseEventArgs e)
    {
        _Down = false;
        button1.Location = e.Location;
    }

    private void button1_MouseMove(object sender, MouseEventArgs e)
    {
        if (_Down)
        {
            button1.Location = e.Location;
        }
    }

This doesn't work either. The effect I get is that when the button is clicked and dragged, the button is not visible until the mouse is released, and also, the button doesn't actually stay at the location of the mouse.

I also tried:

    bool _Down = false;

    private void button1_MouseDown(object sender, MouseEventArgs e)
    {
        _Down = true;
    }

    private void button1_MouseUp(object sender, MouseEventArgs e)
    {
        _Down = false;
        button1.Location = Cursor.Position;
    }

    private void button1_MouseMove(object sender, MouseEventArgs e)
    {
        if (_Down)
        {
            button1.Location = Cursor.Position;
        }
    }

This works better than the first one as the button is visible when dragged and stops at mouse position, but the only problem is that Cursor.Position returns the cursor position in relativeness to the screen, not the form therefore. The button doesn't actually move at the pace of the cursor.

What can I do to achieve what I want?

Upvotes: 1

Views: 315

Answers (2)

King King
King King

Reputation: 63317

Moving Control at runtime is very easy:

Point downPoint;
private void button1_MouseDown(object sender, MouseEventArgs e)
{
    downPoint = e.Location;
}
private void button1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left) {
        button1.Left += e.X - downPoint.X;
        button1.Top += e.Y - downPoint.Y;
    }
}

Upvotes: 2

tdelepine
tdelepine

Reputation: 2016

Try this

private void button1_MouseUp(object sender, MouseEventArgs e)
{
    _Down = false;
    button1.Location = PointToClient(Cursor.Position);
}

private void button1_MouseMove(object sender, MouseEventArgs e)
{
    if (_Down)
    {
        button1.Location = PointToClient( Cursor.Position);
    }
}

Upvotes: 0

Related Questions