原理: (這裡演示縱坐標不變的窗體移動), 兩個 timer, 一個控制從左至右, 到達預先設定的點時觸發另一個 timer,
當然另一個 timer 控制從右至左的移動( 其實質是橫坐標的變化)
如果你希望上下左右或斜線移動甚至亂七八糟(呵呵, 應該叫隨機)只要加足夠的 timer 並控制好橫縱坐標的變換即可.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace ExMoveForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Point p = new Point(0, 240);
this.DesktopLocation = p;
}
private void timer1_Tick(object sender, EventArgs e)
{
//窗體的左上角橫坐標隨著timer1不斷加一
Point p = new Point(this.DesktopLocation.X + 1, this.DesktopLocation.Y);
this.DesktopLocation = p;
if (p.X == 630)
{
timer1.Enabled = false;
timer2.Enabled = true;
}
}
private void timer2_Tick(object sender, EventArgs e)
{
//窗體的左上角橫坐標隨著timer2不斷減一
Point p = new Point(this.DesktopLocation.X - 1, this.DesktopLocation.Y);
this.DesktopLocation = p;
if (p.X == 20)
{
timer1.Enabled = true;
timer2.Enabled = false;
}
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Stop();
timer2.Stop();
}
}
}