Moving a picture box gradually, not instantly

后端 未结 1 708
陌清茗
陌清茗 2021-01-25 06:23

I have an PictureBox that I want to move up on the y axis after a button click. The problem is that the PictureBox simply appears there after the button click. I want it to move

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-25 06:52

    Expanding on BJ Myers comment this is how you can implement that:

    private void button2_Click(object sender, EventArgs e)
    {
        this.timer1.Enabled = true;
    }
    
    private void timer1_Tick(object sender, EventArgs e)
    {    
        // calculate new position
        this.pictureBox1.Top++;
        this.pictureBox1.Left++;
    
        // when to stop
        if (this.pictureBox1.Top > (this.Height - (2 * this.pictureBox1.Height)))
        {
            this.timer1.Enabled = false;
        }
    }
    

    I used the default Timer control that raises a Tick at an interval. The Tick event gets executed on the UI thread so you don't have to be bothered by cross thread errors.

    If added to your form this is what you'll get:

    If you need to animate more stuff you might want to look into using a Background worker and helper classes like I show in this answer of mine

    0 讨论(0)
提交回复
热议问题