要用委托。using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading;
namespace WindowsApplication13 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private delegate void MoveLabel(int val);//声明代理 Thread td; private void Form1_Load(object sender, EventArgs e) { td = new Thread(new ThreadStart(ThreadFun)); td.Start(); } void SetOffset(int val) { label1.Text = "从子线程里传入的值是:" + val.ToString(); } private void ThreadFun() { if (this.InvokeRequired) { MoveLabel d = new MoveLabel(SetOffset); object[] arg = new object[] { 1 };//要传入的参数值 this.Invoke(d, arg); } } } }
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsApplication13
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private delegate void MoveLabel(int val);//声明代理
Thread td;
private void Form1_Load(object sender, EventArgs e)
{
td = new Thread(new ThreadStart(ThreadFun));
td.Start();
}
void SetOffset(int val)
{
label1.Text = "从子线程里传入的值是:" + val.ToString();
}
private void ThreadFun()
{
if (this.InvokeRequired)
{
MoveLabel d = new MoveLabel(SetOffset);
object[] arg = new object[] { 1 };//要传入的参数值
this.Invoke(d, arg);
}
}
}
}
protected delegate string CallBackGetText();
private string GetTxt()
{
if (this.InvokeRequired)
{
CallBackGetText testtxt = new CallBackGetText(GetTxt);
return Convert.Tostring(this.Invoke(testtxt)); }
else
{
return this.textbox1.Text;
}
}
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsApplication15
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private delegate string MoveLabel();//声明代理
Thread td;
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = "123";
td = new Thread(new ThreadStart(ThreadFun));
td.Start();
}
string SetOffset()
{
string str = "取到的值是:" + textBox1.Text;
return str;
}
private void ThreadFun()
{
if (this.InvokeRequired)
{
MoveLabel d = new MoveLabel(SetOffset);
string str = (string)this.Invoke(d);
MessageBox.Show(str);
}
}
}
}