关于C#中自定义事件的使用,举个栗子

首先在设计界面拖入两个按钮,一个文本框。
界面
新建一个类文件(.cs),新建一个事件类型,此处的是产生随机数,并将随机偶数传回,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace WindowsFormsApplication1
{
    //1.声明一个新的事件传递参数函数,继承EventArgs类,是用于触发事件时传递参数
    public class IsEvenEventArgs : EventArgs
    {
        public int Random=0;
        public IsEvenEventArgs(int inputRandom)
        {
            Random = inputRandom;
        }
    }
    //2.声明变更事件的委托类型,需要传递的参数由第一步中声明
    public delegate void IsEvenEvent(object Sender, IsEvenEventArgs e);
    class MyRandom
    {
        //3.声明状态更改事件的名称,使用的是第二步中的委托类型
        public event IsEvenEvent IsEven;
        public void run_Random()
        {
            Random rd = new Random();
            int rad=rd.Next(1,10000);
            //4.在需要的地方拉起事件,同时将参数传递进去
            if (rad % 2 == 0) IsEven(this, new IsEvenEventArgs(rad));
        }
    }

}

接着在界面的关联代码中添加按钮的相应响应函数,此处新建了一个线程,来循环调用前面新建类中的方法,当得到偶数时,此处的响应事件会将此数字打印到textBox上并滚至底部,并使用一个变量来控制线程的进入/退出。

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;
using System.Threading;


namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        bool NeedsStop=true;
        public Form1()
        {
            InitializeComponent();

        }

        private void button2_Click(object sender, EventArgs e)
        {
            NeedsStop = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Thread Mythread = new Thread(Thread_Random);
            Mythread.Start();
            NeedsStop = false;
        }

        private void Thread_Random()
        {
            MyRandom Ran = new MyRandom();
            //5.给事件添加一个响应函数,在事件拉起时调用
            Ran.IsEven += new IsEvenEvent(updateTextBox);
            while (true)
            { 
                Ran.run_Random();
                if (NeedsStop == true) break;
                Thread.Sleep(200);
            }
        }
        //6.在响应函数中使用传递的参数干一些事情
        private void updateTextBox(object Sender, IsEvenEventArgs e)
        {
            textBox1.Invoke
            (
               new Action
               (
                  delegate
                  {
                      string ShowText = "产生了一个随机偶数:" + e.Random.ToString() + "\r\n";
                      textBox1.Text += ShowText;
                      textBox1.Focus();//获取焦点
                      textBox1.Select(this.textBox1.TextLength, 0);//光标定位到文本最后
                      textBox1.ScrollToCaret();//滚动到光标处
                  }
               )
            );
        }
    }
}

举的小例子整体实现的效果是,按下开始按钮开始产生随机数并在文本框中更新偶数,按下停止按钮时停止更新。按照注解中的6步可以很轻松的使用C#中的自定义事件。

猜你喜欢

转载自blog.csdn.net/li3781695/article/details/84981827
今日推荐