110,566
社区成员
发帖
与我相关
我的任务
分享
private void btnStart_Click(object sender, EventArgs e)
{
LabThreadMove(label1, new Point(50, 200)); //label1 移动
LabThreadMove(label2, new Point(150, 200)); //label2 移动
LabThreadMove(label3, new Point(260, 200)); //label3 移动
}
public void LabThreadMove(Label lab, Point point)
{
new Thread(delegate () //开后台线程执行移动方法
{
while (LabMove(lab, point)) { Thread.Sleep(10); }
})
{ IsBackground = true }.Start();
}
public bool LabMove(Label lab, Point point)
{
bool isMove = true;
this.Invoke((EventHandler)delegate
{
if (lab.Location == point) isMove = false;
Point curPoint = lab.Location;
if (curPoint.X != point.X)
curPoint.X = curPoint.X - point.X < 0 ? curPoint.X += 1 : curPoint.X -= 1;
if (curPoint.Y != point.Y)
curPoint.Y = curPoint.Y - point.Y < 0 ? curPoint.Y += 1 : curPoint.Y -= 1;
lab.Location = curPoint;
});
return isMove;
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Control[] ctls = new Control[] {
new Button(){Text="btn1"},
new Button(){Text="btn2",Left=100},
new Button(){Text="btn3",Left=200},
};
private void Form1_Load(object sender, EventArgs e)
{
this.Controls.AddRange(ctls);
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
t.Interval = 500;
t.Enabled = true;
t.Tick += timer1_Tick;
}
private void button1_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
//btn1移动
ctls[0].Top += 5;
//btn2移动
ctls[1].Top += 5;
ctls[1].Left+= 5;
//btn3移动
ctls[2].Top += 5;
ctls[2].Left += -3;
}
}
并不需要很多个线程。