Controling the Moving PictureBox

后端 未结 2 1648
误落风尘
误落风尘 2020-12-12 05:38

So, I am kinda stucked on my moving PICTURE box; at the moment my form 2 loads the picture box starts moving, that is exactly what I wanted, However it isn\'t in my Control

相关标签:
2条回答
  • 2020-12-12 06:14

    The timer events are being raised on the UI thread, thus the key press events aren't being picked up fast enough.

    Run the timer on a background thread, and it should work. Just remember that the timer will then be making cross thread calls, thus you need to make use of Control.InvokeRequired

    0 讨论(0)
  • 2020-12-12 06:25

    You need a variable that indicates in which direction the box is moving:

        private enum Direction { None, Left, Right, Up, Down };
        private Direction currentDir = Direction.None;
    

    The timer's Tick event needs to check this variable to know in which direction to move the box:

        private void timer1_Tick(object sender, EventArgs e) {
            int vel = 5;
            switch (currentDir) {
                case Direction.Left:  pictureBox1.Left -= Math.Min(vel, pictureBox1.Left); break;
                case Direction.Right: pictureBox1.Left += Math.Min(vel, this.ClientSize.Width - pictureBox1.Right); break;
                case Direction.Up:    pictureBox1.Top  -= Math.Min(vel, pictureBox1.Top); break;
                case Direction.Down:  pictureBox1.Top  += Math.Min(vel, this.ClientSize.Height - pictureBox1.Bottom); break;
            }
        }
    

    Your KeyDown event handler should simply set the variable:

        private void Form1_KeyDown(object sender, KeyEventArgs e) {
            switch (e.KeyData) {
                case Keys.Left:  currentDir = Direction.Left; break;
                case Keys.Right: currentDir = Direction.Right; break;
                case Keys.Up:    currentDir = Direction.Up; break;
                case Keys.Down:  currentDir = Direction.Down; break;
            }
        }
    

    You also need the KeyUp event, it should stop moving the box again:

        private void Form1_KeyUp(object sender, KeyEventArgs e) {
            switch (e.KeyData) {
                case Keys.Left:  if (currentDir == Direction.Left)  currentDir = Direction.None; break;
                case Keys.Right: if (currentDir == Direction.Right) currentDir = Direction.None; break;
                case Keys.Up:    if (currentDir == Direction.Up)    currentDir = Direction.None; break;
                case Keys.Down:  if (currentDir == Direction.Down)  currentDir = Direction.None; break;
            }
        }
    
    0 讨论(0)
提交回复
热议问题