工具:
- 实例采用VS2017编写
操作:
在 public Form1() 函数中设置检测跨线程调用为假:
public Form1() { InitializeComponent(); //设置 检查非法跨线程调用 为 false CheckForIllegalCrossThreadCalls = false; }
声明 线程调用窗口组件的委托
private delegate void MyDelegateUI();
在线程函数中实现委托修改
//定义委托 MyDelegateUI s = delegate { label1.Text = "新标题"; }; //执行委托 label1.Invoke(s);
完整代码:
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 wt { public partial class Form1 : Form { public Form1() { InitializeComponent(); //设置 检查非法跨线程调用 为 false CheckForIllegalCrossThreadCalls = false; } //声明线程调用窗口组件的委托 private delegate void MyDelegateUI(); private void button1_Click(object sender, EventArgs e) { Thread xc = new Thread(xg); xc.Start(); } private void xg(object data) { //定义委托 MyDelegateUI s = delegate { label1.Text = textBox1.Text; }; //执行委托 label1.Invoke(s); } } }