一、主窗体代码:多线程
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; namespace _08委托与多线程实现窗体间传值 { public delegate void SetTextDel(string text);//声明 public partial class MainFrm : Form { public MainFrm() { InitializeComponent(); this.Text = Thread.CurrentThread.ManagedThreadId.ToString();//当前线程ID //线程间空间不能相互访问,容许其余线程来访问当前线程建立的 控件:Control //Control.CheckForIllegalCrossThreadCalls = false;//掩耳盗铃的方式 } private void button1_Click(object sender, EventArgs e) { //ChildFrm child = new ChildFrm(); //child.setTextDel = SetText;//实例化 //child.Show(); //方法二:多线程 Thread thread = new Thread(() => { ChildFrm child = new ChildFrm(); child.setTextDel = SetText;//实例化 child.ShowDialog(); }); thread.Start();//要开启,告诉操做系统已经准备就绪,随时能够调用 } private void SetText(string text) { //InvokeRequired 当线程执行到此的时候,校验一下txtMessage控件是哪一个线程建立的。 //若是是本身建立的InvokeRequired:fasle反之则为true if (this.txtMessage.InvokeRequired)//不是本身建立的 { SetTextDel setTextDel = SetTextForOtherThread; this.Invoke(setTextDel,text);//Invoke(委托名,参数) } else { this.txtMessage.Text = text; } } private void SetTextForOtherThread(string text) { this.txtMessage.Text = text; } } }
二、子窗体代码:ide
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; namespace _08委托与多线程实现窗体间传值 { public partial class ChildFrm : Form { public ChildFrm() { InitializeComponent(); this.Text = Thread.CurrentThread.ManagedThreadId.ToString(); } public SetTextDel setTextDel = null;//初始化 private void btnSetMainTxt_Click(object sender, EventArgs e) { if (setTextDel != null) { setTextDel(this.txtSource.Text);//调用 } } } }
三、运行截图:ui