事件

Posted on 2019-12-07 20:13  冰糖Luck1996  阅读(110)  评论(0编辑  收藏  举报

实现效果:

1,创建两个窗体

 

 FormMain

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;

namespace 事件
{
    public delegate void Method(string info);
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }
        public List<FormSon> sons = new List<FormSon>();
        public void EventMethod(string info)
        {
            this.textBox1.Text = info;
        }

        /// <summary>
        /// 初始化创建3个子窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormMain_Load(object sender, EventArgs e)
        {
            for (int i = 0; i < 3; i++)
            {
            FormSon formSon = new FormSon();
            formSon.Location = new Point(300*(i+1),300);
            sons.Add(formSon);
            formSon.Show();
            }
        }
        /// <summary>
        /// 关联事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            foreach (var item in sons)
            {
                //事件不可以赋空值
                //事件只能通过+=或者-=与方法关联或移除R
                item.method += EventMethod;
            }
        }
        /// <summary>
        /// 移除事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            foreach (var item in sons)
            {
                item.method -= EventMethod;
            }
        }
    }
View Code

FormSon

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;

namespace 事件
{
    public partial class FormSon : Form
    {
        public FormSon()
        {
            InitializeComponent();
        }
        //创建事件
        public event Method method;

        private void button1_Click(object sender, EventArgs e)
        {
            if (method==null)
            {
                MessageBox.Show("请先关联事件");
                return;
            }
            
            method(this.textBox1.Text);
        }
    }
}
View Code