试图在计时器上移动图片控件

时间:2013-12-25 00:01:24

标签: c# winforms

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Game2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            timer1.Start();
        }

        private void Move_Ship(int X_Coord ,int Y_Coord, string Positioning)
        {
            if(Positioning == "Rechts")
            {
                X_Coord += 5;
                this.pictureBox1.Location = new Point(X_Coord, Y_Coord);
            };

            if (Positioning == "Links")
            {
                X_Coord -= 5;
                this.pictureBox1.Location = new Point(X_Coord, Y_Coord);
            };

            if (Positioning == "Up")
            {
                Y_Coord -= 5;
                this.pictureBox1.Location = new Point(X_Coord, Y_Coord);
            };

            if (Positioning == "Down")
            {
                Y_Coord += 5;
                this.pictureBox1.Location = new Point(X_Coord, Y_Coord);
            };
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (Control.ModifierKeys == Keys.Up)
            {
                Move_Ship(pictureBox1.Location.X, pictureBox1.Location.Y, "Up");
            };

            if (Control.ModifierKeys == Keys.Down)
            {
                Move_Ship(pictureBox1.Location.X, pictureBox1.Location.Y, "Down");
            };

            if (Control.ModifierKeys == Keys.Left)
            {
                Move_Ship(pictureBox1.Location.X, pictureBox1.Location.Y, "Links");
            };

            if (Control.ModifierKeys == Keys.Right)
            {
                Move_Ship(pictureBox1.Location.X, pictureBox1.Location.Y, "Rechts");
            };           
        }
    }
}

如果我做得对,我的piture应该移动,但它根本不做任何事情。 我做错了什么,如果有的话请告诉我?

1 个答案:

答案 0 :(得分:2)

一个可能的问题是使用Control.ModifierKeys

  

获取一个值,指示哪个修饰键(SHIFT,CTRL和ALT)处于按下状态。

如果你想使用方向键 - 听取keyDown事件并在那里保存方向。样本和详细信息Control.KeyDown

  private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
  {
     // Determine whether the keystroke is a number from the top of the keyboard. 
     if (e.KeyCode == Keys.Down)
     { 
        direction = "Down";
     }