委托与事件

两个窗体form1和form2
点击form1按钮跳转到form2
点击form2按钮,form1中按钮文字变化

form1中代码

namespace TestUI
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2();
            form2.settxt += SetBtnText;
            form2.Show();
        }

        public void SetBtnText(string txt)
        {
            button1.Text = txt;
        }
    }
}

form2中代码

namespace TestUI
{
    public partial class Form2 : Form
    {
        public delegate void SetTextToBtn(string txt);

        public Form2()
        {
            InitializeComponent();
        }

        public event SetTextToBtn settxt;

        private void button1_Click(object sender, EventArgs e)
        {
            string txt = "2018 新年快乐";
            settxt(txt);
        }
    }
}

你可能感兴趣的:(委托与事件)