C# 窗体调用和回调

方法一:直接传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);
        }
    }

你可能感兴趣的:(c#,c#,visual,studio)