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

时间:2021-07-05 16:39:05   收藏:0   阅读:0

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();
        }
    }
}

效果

技术图片

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

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!