一个泡泡的随机运动
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 窗体移动
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//加载一个窗体事件
this.Load+=new EventHandler(Form1_Load);
//timer的Tick事件
t.Tick += new EventHandler(t_Tick);
}
//实例化一个Timer对象
Timer t=new Timer();
//定义两个变量
int b1=0,b2=0;
//timer的Tick事件
void t_Tick(object sender, EventArgs e)
{
//throw new NotImplementedException();
this.Left += b2;
this.Top += b1;
//当窗体碰撞到窗体上边界或下边界控制上下的变量*-1
if (this.Top <= 0 || this.Bottom >= Screen.PrimaryScreen.WorkingArea.Height)
{
b1 *= -1;
}
//当窗体碰撞到窗体左边界或右边界控制上下的变量*-1
if (this.Left <= 0 || this.Right >= Screen.PrimaryScreen.WorkingArea.Width)
{
b2 *= -1;
}
}
//窗体加载事件
private void Form1_Load(object sender, EventArgs e)
{
//改变窗体透明度
this.Opacity = 0.7;
//将窗体解成一个椭圆
GraphicsPath g = new GraphicsPath();
g.AddEllipse(0,0,this.Width,this.Height);
this.Region = new Region(g);
//窗体的初始位置为(0,0)
this.Location = new Point(0, 0);
//生成两个随机数
Random a = new Random();
b1 = a.Next(2, 8);
b2 = a.Next(2, 8);
//启动timer并设置频率为10ms
t.Interval = 10;
t.Start();
}
}
}
多个泡泡的随机运动
同一个泡泡运动原理相同,可多实例化几个窗口,这里作者提供一个方法
void showform(Form s,int b3,int b4)
{
s.Location = new Point(s.Location.X + b3, s.Location.Y + b4);
if (s.Location.Y <= 0 || s.Location.Y >= Screen.PrimaryScreen.WorkingArea.Height-s.Height)
{
b4 *= -1;
}
else if (s.Location.X <= 0 || s.Location.X >= Screen.PrimaryScreen.WorkingArea.Width-s.Width)
{
b3 *= -1;
}
}