窗體和控件的一個小實驗:控制一個飛機左右移動

一:內容:

窗體上兩個按鈕:開始和停止,一個PictureBox,PictureBox中放一飛機圖片。單擊“開始”,則飛機圖片左右在窗體上移動,移動到窗體邊界時,反轉方向移動。單擊“停止”按鈕,則飛機回到初始位置(窗體左側)並停止移動。

窗體設置如下:


 int X, Y;
        public Form4()
        {
            InitializeComponent();
            X = pictureBox1.Location.X;
            Y = pictureBox1.Location.Y;
            
        }


timer1代碼:

 private void timer1_Tick(object sender, EventArgs e)
        {
            pictureBox1.Left += 10;
            if (pictureBox1.Left +pictureBox1.Width>= this.Width)
            {
                timer1.Enabled = false;
                timer2.Enabled = true;
            
            }
        }

timer2代碼:

  private void timer2_Tick(object sender, EventArgs e)
        {
            pictureBox1.Left -= 10;
            if (pictureBox1.Left <= 0)
            {
                timer1.Enabled = true;
                timer2.Enabled = false;
              
            }
        }

開始代碼:

    private void button1_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true; 
            timer2.Enabled = false;
        }



停止代碼:

 private void button2_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            pictureBox1.Left = X;
            pictureBox1.Top = Y;
            timer2.Enabled = false;
        }
    }

運行圖如下:


點停止如下:





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章