下面这个是碰到边界回弹示例,对角线首先label得放到对角线上,代码计算出来会跳动
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp8
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
t = new Timer();
t.Enabled = false;
t.Interval = 100;//100ms移动一次
t.Tick += T_Tick;
}
int x = 5, y = 5;
private void T_Tick(object sender, EventArgs e)
{
label1.Location = new Point(label1.Location.X + x, label1.Location.Y+y);
if (label1.Location.X > this.ClientRectangle.Width - label1.Width || label1.Location.X < 0) x = -x;
if (label1.Location.Y > this.ClientRectangle.Height - label1.Height || label1.Location.Y < 0) y = -y;
}
Timer t;
private void textBox1_TextChanged(object sender, EventArgs e)
{
label1.ForeColor = Color.FromName(textBox1.Text);
}
private void button1_Click(object sender, EventArgs e)
{
t.Enabled = button1.Text=="移动";
button1.Text = t.Enabled ? "停止" : "移动";
}
}
}