「已注销」 2021-06-29 09:18 采纳率: 100%
浏览 92
已结题

c#产生随机圆随机半径随机位置

 

  • 写回答

3条回答 默认 最新

  • CSDN专家-文盲老顾 2021-06-29 09:54
    关注
    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);
                    }));
                }
            }
        }
    }
    

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?