C#中在线程中访问主Form控件的问题

C#不允许直接从线程中访问Form里的控件,比如希望在线程里修改Form里的一个TextBox的内容等等,唯一的做法是使用Invoke方法,下面是一个MSDN里的Example,很说明问题:

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;

public class MyFormControl:Form
... {
publicdelegatevoidAddListItem(StringmyString);
publicAddListItemmyDelegate;
privateButtonmyButton;
privateThreadmyThread;
privateListBoxmyListBox;
publicMyFormControl()
...{
myButton
=newButton();
myListBox
=newListBox();
myButton.Location
=newPoint(72,160);
myButton.Size
=newSize(152,32);
myButton.TabIndex
=1;
myButton.Text
="Additemsinlistbox";
myButton.Click
+=newEventHandler(Button_Click);
myListBox.Location
=newPoint(48,32);
myListBox.Name
="myListBox";
myListBox.Size
=newSize(200,95);
myListBox.TabIndex
=2;
ClientSize
=newSize(292,273);
Controls.AddRange(
newControl[]...{myListBox,myButton});
Text
="'Control_Invoke'example";
myDelegate
=newAddListItem(AddListItemMethod);
}

staticvoidMain()
...{
MyFormControlmyForm
=newMyFormControl();
myForm.ShowDialog();
}

publicvoidAddListItemMethod(StringmyString)
...{
myListBox.Items.Add(myString);
}

privatevoidButton_Click(objectsender,EventArgse)
...{
myThread
=newThread(newThreadStart(ThreadFunction));
myThread.Start();
}

privatevoidThreadFunction()
...{
MyThreadClassmyThreadClassObject
=newMyThreadClass(this);
myThreadClassObject.Run();
}

}

public class MyThreadClass
... {
MyFormControlmyFormControl1;
publicMyThreadClass(MyFormControlmyForm)
...{
myFormControl1
=myForm;
}

StringmyString;

publicvoidRun()
...{


for(inti=1;i<=5;i++)
...{
myString
="Stepnumber"+i.ToString()+"executed";
Thread.Sleep(
400);
//Executethespecifieddelegateonthethreadthatowns
//'myFormControl1'control'sunderlyingwindowhandlewith
//thespecifiedlistofarguments.
myFormControl1.Invoke(myFormControl1.myDelegate,
newObject[]...{myString});
}

}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值