1. 程式人生 > >winform 利用事件在窗體間傳值

winform 利用事件在窗體間傳值

執行結果如下:

實現部分;建立兩個form窗體,Form1,Form2;建立一個類MyEventArg.cs.

MyEventArg.cs程式碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace weituo
{
    public class MyEventArg:EventArgs
    {
        public string Text { get; set; }
        public string Name { get; set; }
    }
}

Form1介面程式碼:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace weituo
{
    public partial class Form1 : Form
    {
        #region
        public event EventHandler SendMsgEvent;//使用預設的事件使用委託
        #endregion
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
           /* #region
            Form2 form2 = new Form2();
            SendMsgEvent += form2.MainFormTxtChaned;
            form2.Show();
            this.Hide();
            #endregion*/
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2();
            SendMsgEvent += form2.MainFormTxtChaned;
            form2.Show();
           // this.Hide();
            SendMsgEvent(this, new MyEventArg() { Text = this.textBox1.Text, Name=this.textBox2.Text });
        }
    }
}

form2介面程式碼:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace weituo
{


    public partial class Form2 : Form
    {
        public void SetText(string txt,string name)
        {
            this.textBox1.Text = txt;
            this.textBox2.Text = name;
        }
        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {

        }
      

        internal void MainFormTxtChaned(object sender,EventArgs e)
        {
            MyEventArg arg = e as MyEventArg;
            this.SetText(arg.Text, arg.Name);
        }
    }
}