C#桌面两球体随机移动效果源码
新建winform窗体,添加timer并绑定事件
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace test.winForm
{
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
}
private void Form4_Load(object sender, EventArgs e)
{
//设置窗体初始位置
this.Location = new Point(0, 0);
//去掉窗体边框
this.FormBorderStyle = FormBorderStyle.None;
//设置窗体大小
this.Size = new Size(300, 300);
//设置窗体背景颜色
this.BackColor = Color.Pink;
//设置窗体不透明度
this.Opacity = 2.9;
//将窗体变为圆形
GraphicsPath path = new GraphicsPath();
path.AddEllipse(0, 0, this.Width, this.Height);
this.Region = new Region(path);
//设置计时器频率
timer1.Interval = 10;
//开启计时器
timer1.Start();
}
//定义两个局部变量
int x = 8;
int y = 8;
Random ys = new Random();
private void timer1_Tick(object sender, EventArgs e)
{
//窗体距容器左距离
this.Left += x;
//窗体距容器上距离
this.Top += y;
//窗体碰到容器下方和上方
if (this.Top + this.Height >= Screen.PrimaryScreen.WorkingArea.Height || this.Top <= 0)
{
//取反,加y变成减y
y = -y;
this.BackColor = Color.FromArgb(ys.Next(256), ys.Next(256), ys.Next(256));
}
//窗体碰到容器右方和左方
if (this.Left + this.Width >= Screen.PrimaryScreen.WorkingArea.Width || this.Left <= 0)
{
//取反,加x变成减x
x = -x;
this.BackColor = Color.FromArgb(ys.Next(0, 255), ys.Next(0, 255), ys.Next(0, 255));
}
}
}
}
再加一个窗体,同样添加timer和绑定事件
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace test.winForm { public partial class Form3 : Form { public Form3() { InitializeComponent(); } private void Form3_Load(object sender, EventArgs e) { //设置窗体初始位置 this.Location = new Point(0, 0); //去掉窗体边框 this.FormBorderStyle = FormBorderStyle.None; //设置窗体大小 this.Size = new Size(200, 200); //设置窗体背景颜色 this.BackColor = Color.Red; //设置窗体不透明度 this.Opacity = 2.9; //将窗体变为圆形 GraphicsPath path = new GraphicsPath(); path.AddEllipse(0, 0, this.Width, this.Height); this.Region = new Region(path); //设置计时器频率 timer1.Interval = 10; //开启计时器 timer1.Start(); Form4 fm2 = new Form4(); fm2.Show(); } //定义两个局部变量 int x = 7; int y = 7; Random ys = new Random(); private void timer1_Tick(object sender, EventArgs e) { //窗体距容器左距离 this.Left += x; //窗体距容器上距离 this.Top += y; //窗体碰到容器下方和上方 if (this.Top + this.Height >= Screen.PrimaryScreen.WorkingArea.Height || this.Top <= 0) { //取反,加y变成减y y = -y; this.BackColor = Color.FromArgb(ys.Next(256), ys.Next(256), ys.Next(256)); } //窗体碰到容器右方和左方 if (this.Left + this.Width >= Screen.PrimaryScreen.WorkingArea.Width || this.Left <= 0) { //取反,加x变成减x x = -x; this.BackColor = Color.FromArgb(ys.Next(0, 255), ys.Next(0, 255), ys.Next(0, 255)); } } } }
启动方法中设置启动窗体为form3运行起来即可

浙公网安备 33010602011771号