标签:
假设winform中有两个控件:
1.ListView用来显示进度的文本提示,ID:listView_progressInfo
2.ProgressBar用来显示进度,ID:progressBar1
在此winform的后台.cs文件中声明两个公用委托类型:ControlChanger, ProgressChanger
public delegate void ControlChanger(string progressText);
public delegate void ProgressChanger(int current, int total);
并且编写操作上面两个控件的函数,它们都在此winform的线程内运行,故修改控件时不会报“非创建控件的线程不可修改控件”的错误:
public void AddProgressIntoListView(string text)
{
if (listView_progressInfo.InvokeRequired)
{
ControlChanger outdelegate = new ControlChanger(AddProgressIntoListView);
this.BeginInvoke(outdelegate, new object[] { text });
return;
}
listView_progressInfo.Items.Add(new ListViewItem(text));
}
public void SetProgressBarValue(int current, int total)
{
if (progressBar1.InvokeRequired)
{
ProgressChanger outdelegate = new ProgressChanger(SetProgressBarValue);
this.BeginInvoke(outdelegate, new object[] { current, total });
return;
}
progressBar1.Value = (int)(100 * current / total);
}
检查控件InvokeRequired属性是为了保证安全地访问控件,参考微软知识库:
https://msdn.microsoft.com/en-us/library/ms171728(v=vs.110).aspx
新建一个类用来操作winform中的控件:
public class ControlChange
{
public ControlChanger cc = null;
public ProgressChanger pc = null;
public void ChangeControlAndProgress()
{
int taskCount = 100;
for (int i = 0; i <= taskCount; i++)
{
if (null != cc)
{
cc(string.Format("任务进行中,进度{0}%", i));
}
if (null != cc)
{
pc(i,taskCount);
}
System.Threading.Thread.Sleep(500);
}
}
}
然后在触发器中(可以是一个按钮)写入如下代码:
private void button_start_Click(object sender, EventArgs e)
{
ControlChange controlchange = new ControlChange();
controlchange.cc = new ControlChanger(AddProgressIntoListView);//将ControlChanger委托类型的变量cc实例化
controlchange.pc = new ProgressChanger(SetProgressBarValue);//将ProgressChanger委托类型的变量cc实例化
new Thread(new ThreadStart(controlchange.ChangeControlAndProgress)).Start();//新建线程来运行ControlChange中的修改控件的方法ChangeControlAndProgress
}
触发器触发后即可看到窗体中的进度提示和进度条在走。
标签:
原文地址:http://www.cnblogs.com/vaecole/p/changeControlsInOtherThread_Winform.html