C# 窗体调用和回调

文章介绍了在C#的WindowsForms应用中,如何在Form1和Form2之间传递数据,包括直接传this调用公共方法、使用委托以及利用事件的方式。每种方法都提供了详细的代码示例,展示了如何修改和操作控件文本。
摘要由CSDN通过智能技术生成

方法一:直接传this,方法设为public

Form1代码:
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            new Form2("hello world",this).Show();
        }
        public void SetTextBox(string str)
        {
            textBox1.Text = str;
        }
    }

Form2代码:
    public partial class Form2 : Form
    {
        Form1 m_f1;
        string m_str;
        public Form2(string str, Form1 f1)
        {
            InitializeComponent();
            m_str = str;
            m_f1 = f1;
        }
        private void Form2_Load(object sender, EventArgs e)
        {
            m_f1.SetTextBox(m_str);
        }
    }

方法二:委托

Form1代码:
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2();
            f2.Show();
            f2.CallBackFun("hello world", SetTextBox);
        }
        public void SetTextBox(string str)
        {
            textBox1.Text = str;
        }
    }
Form2代码:
    public partial class Form2 : Form
    {
        public delegate void DelegateFun(string str);
        public Form2()
        {
            InitializeComponent();
        }
        public void CallBackFun(string str, DelegateFun delegateFun)
        {
            delegateFun(str);
        }
    }

方法三:委托、事件

Form1代码:
    public partial class Form1 : Form
    {
        private Form2 f2;
        public Form1()
        {
            InitializeComponent();
        }
        private void ShowMsgFun(string str)
        {
            textBox1.Text = str;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            f2 = new Form2("hello world");
            f2.ShowCallBack += ShowMsgFun;
            f2.Show();
        }
    }
Form2代码:
    public partial class Form2 : Form
    {
        private string m_showMsg;
        //委托
        public delegate void CallBack(string str);
        //事件
        public event CallBack ShowCallBack;
        public Form2(string showMsg)
        {
            InitializeComponent();
            m_showMsg = showMsg;
        }
        private void Form2_Load(object sender, EventArgs e)
        {
            ShowFun(m_showMsg);
        }
        public void ShowFun(string showMsg)
        {
            ShowCallBack(showMsg);
        }
    }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值