C# 通过委托,事件窗口传值

Form2

namespace WindowsFormsApp1
{
    //定义委托
    public delegate void Sum(int x, int y);
    public partial class Form2 : Form
    {
        //定义事件
        public event Sum sum;
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int x = Convert.ToInt32(textBox1.Text);
            int y = Convert.ToInt32(textBox2.Text);
            sum(x, y);
        }
    }
}

Form1

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

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2();
            //注册事件
            form2.sum += sum;
            form2.ShowDialog();
        }
        //计算
        public void sum(int x ,int y)
        {
            textBox1.Text = (x + y).ToString();
        }
    }
}

效果

img

//网络素材仅限收藏 方便学习

posted @ 2021-07-02 15:08  New_HackerHK  阅读(87)  评论(0编辑  收藏  举报