我需要帮助Update From(); (Windows窗体应用程序)

时间:2010-08-02 03:35:53

标签: c# forms

嘿,我无法弄清楚如何创建更新表单的对象。 (Windows窗体应用程序)。我正在从一本要求我制作狗赛车计划的书中做一个项目。 我需要更新狗的图片框,以便他们移动。谢谢你的帮助!

1 个答案:

答案 0 :(得分:2)

执行此操作的简单方法是执行以下步骤:

  1. 将对象添加到System.Windows.Forms.Timer
  2. 的表单中
  3. 设置它的间隔。
  4. 将其设置为true。
  5. 创建一个响应Tick事件的事件处理程序。
  6. 在事件处理程序中,您可以移动图片框。您可能希望为每个图片框存储随机数以确定移动速度。你还需要一种方法来限制盒子移动的形式。

    以下是代码形式的概念证明:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
    
            _rate = new Random().Next(1, 10);
    
            _timer = new Timer() { Interval = 100, Enabled = true };
            _timer.Tick += new EventHandler(timer_Tick);
        }
    
        void timer_Tick(object sender, EventArgs e)
        {
            if (this.pictureBox1.Location.X > (this.Size.Width - this.pictureBox1.Size.Width))
            {
                return;
            }
    
            Point newLocation = this.pictureBox1.Location;
            newLocation.X += _rate;
            this.pictureBox1.Location = newLocation;
        }
    
        private int _rate;
        private Timer _timer;
    }
    

    public partial class Form1 : Form { public Form1() { InitializeComponent(); _rate = new Random().Next(1, 10); _timer = new Timer() { Interval = 100, Enabled = true }; _timer.Tick += new EventHandler(timer_Tick); } void timer_Tick(object sender, EventArgs e) { if (this.pictureBox1.Location.X > (this.Size.Width - this.pictureBox1.Size.Width)) { return; } Point newLocation = this.pictureBox1.Location; newLocation.X += _rate; this.pictureBox1.Location = newLocation; } private int _rate; private Timer _timer; }