C#跨线程更改用户界面
这里举一个更改Text属性的例子:
1.为了实现更改任意一个控件,这里我定义了一个结构体
public struct SetTextParam
{
public Control CtrlObject;
public string strText;
}
2.定义一个委托
delegate void SetTextCallback(SetTextParam stParam);
3.编写改变Text属性的函数
private void SetText(SetTextParam stParam)
{
if (stParam.CtrlObject.InvokeRequired)
stParam.CtrlObject.Invoke(new SetTextCallback(SetText), new object[] { stParam });
else
stParam.CtrlObject.Text = stParam.strText;
}
重载一个,我更喜欢这样的方式:
private void SetText(Control CtrlObject,string strText)
{
if (CtrlObject.InvokeRequired)
{
SetTextParam stParam;
stParam.CtrlObject = CtrlObject;
stParam.strText = strText;
CtrlObject.Invoke(new SetTextCallback(SetText), new object[] { stParam });
}
else
CtrlObject.Text = strText;
}
4.创建线程函数
private void ThreadProcSafe(object objParam)
{
SetText((SetTextParam)objParam);
}
5.现在可以在别的线程里面改变Control的界面了,如在button1_click中添加如下代码:
SetTextParam stParam;
stParam.CtrlObject = button1;
stParam.strText = "New Button";
Thread newThread = new Thread(new ParameterizedThreadStart(ThreadProcSafe));
newThread.Priority = ThreadPriority.AboveNormal;
newThread.Start(stParam);
posted on 2013-02-20 10:16 HOT SUMMER 阅读(337) 评论(0) 编辑 收藏 举报