using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
namespace test
{
public partial class Form2 : Form
{
private Random rnd = new Random();
public Form2()
{
InitializeComponent();
}
/// 按钮事件请在按钮上进行绑定,或在InitializeComponent里添加事件
private void button1_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
if (btn.Text == "开始")
{
btn.Text = "结束";
for (int i = 0; i < 100; i++)
{
Thread th = new Thread(new ThreadStart(DrawCircle));
th.Start();
}
}
else
{
btn.Text = "开始";
}
}
private void DrawCircle()
{
while (true)
{
// 线程等待,避免资源消耗过多,窗体其他控件无法响应
Thread.Sleep(100);
// 当点击停止按钮后,按钮文字变成开始,线程内检测到按钮文字是开始时,退出线程
if (button1.Text == "开始")
{
return;
}
// 线程内更改窗体内容时,请使用委托
this.Invoke(new MethodInvoker(delegate
{
// 用随机数设置颜色,位置,大小,并画到窗体上
int x = rnd.Next(1, this.Width);
int y = rnd.Next(1, this.Height);
int w = rnd.Next(3, 20);
int h = w;
Graphics g = this.CreateGraphics();
Pen p = new Pen(Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255)), 2);
g.DrawEllipse(p, x, y, w, h);
}));
}
}
}
}
用随机数产生就行,自己可以控制随机数的范围
Random ran = new Random();
int n = ran.Next(100, 1000);
具体化出来可以参考:C# GDI练习 随机线段+随机圆_广大菜鸟的博客-CSDN博客
为什么要启用100个线程,硬掰上关系吗?