我需要一些指导,说明为什么这不起作用:
所以这就是问题,我想给我的用户一个小的状态字段,以便他们可以检查需要多长时间并为他们喝一两杯咖啡。
我的问题是statusfield
(2个标签)在此过程中未更新。
这是我目前的代码:
private void Cancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void start_change_Click(object sender, EventArgs e)
{
DialogResult dr = MessageBox.Show("Start process?", "DateChanger", MessageBoxButtons.OKCancel, MessageBoxIcon.Hand);
if (dr == DialogResult.OK)
{
//get files
List<String> d = new List<String>();
label_status_title.Text = "Status: collecting Data, take a coffee while waiting.\nfiles changed: 0 files";
d = getFiles("H:\\");
int i = 0;
double diff = 0.0;
//modify files
label_status_title.Text = "Status: changing files.\nfiles changed: 0/" + d.Count + " files.";
foreach (String s in d)
{
String label = "\nfile: " + s;
//create newDate and modify creation and lastwrite
DateTime actualDate = Directory.GetLastWriteTime(s).Date;
DateTime newDate = new DateTime(2015, 03, 01);
diff = (newDate - actualDate).TotalDays;
label += "\nactual creation date: " + Directory.GetCreationTime(s).Date;
label += "\nnew creation date: " + newDate.Date;
label += "\nactual last write date: " + Directory.GetLastWriteTime(s).Date;
label += "\nnew last write date: " + newDate.Date;
if (diff > 400)
{
try
{
//set new timevalues
Directory.SetCreationTime(s, newDate);
Directory.SetCreationTimeUtc(s, newDate);
Directory.SetLastWriteTime(s, newDate);
Directory.SetLastWriteTimeUtc(s, newDate);
}
catch (UnauthorizedAccessException UAE)
{
}
i++;
label += "\nchange needed.";
}
else
{
label += "\nchange not needed.";
}
label_status.Text = label;
label_status_title.Text = "Status: changing files.\nfiles changed: " + i + "/" + d.Count + " files.";
}
MessageBox.Show("Process finished, changed: " + i + "/" + d.Count + " files.");
}
}
private List<String> getFiles(string sDir)
{
List<String> files = new List<String>();
try
{
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(getFiles(d));
}
}
catch (System.Exception excpt)
{
MessageBox.Show(excpt.Message);
}
return files;
}
private void DateChanger_Load(object sender, EventArgs e)
{
String label = "";
label_status_title.Text = "Status: \nfiles changed: 0 files";
label += "file: ";
label += "\nactual creation date: ";
label += "\nnew creation date: ";
label += "\nactual last write date: ";
label += "\nnew crealast writetion date: ";
label_status.Text = label;
}
我也尝试过使用MethodInvoker
的建议,但这也没有用。任何指导或建议都表示赞赏。
感谢。
的Mirko
P.S。如果有比使用标签或文本框更好的解决方案,请随时告诉我。 :)
答案 0 :(得分:1)
Youre方法start_change_Click(对象发送者,EventArgs e)正在阻塞主线程。要避免这种情况,请使用单独的线程更新标签。 看看这篇文章:Thread freezes main UI
答案 1 :(得分:-1)
在为其分配新的文本值后,只需刷新标签。
label_status_title.Text = "Status: changing files.\nfiles changed: " + i + "/" + d.Count + " files.";
label_status_title.Refresh(); //added