ProgressForm 类:
public partial class ProgressForm : Form
{
public int prc = 0, sz;
MainForm mf;
public ProgressForm(MainForm MF)
{
InitializeComponent();
mf = MF;
sz = 0;
}
public ProgressForm(int mx)
{
InitializeComponent();
sz = mx;
}
public void SetMax(int mx)
{
sz = mx;
}
public void StartProgress()
{
timer1.Enabled = true;
}
public void IncProgress(int prg)
{
prc += prg;
}
private void timer1_Tick(object sender, EventArgs e)
{
double pos = (double)prc / (double)sz * 100;
progressBar.Value = (int)pos;
}
private void ProgressForm_FormClosing(object sender, FormClosingEventArgs e)
{
timer1.Enabled = false;
}
private void cancelBtn_Click(object sender, EventArgs e)
{
mf.isCanceled = true;
this.Close();
}
private void ProgressForm_Shown(object sender, EventArgs e)
{
progressBar.Value = 0;
StartProgress();
}
}
MainForm 类:
void DeleteFiles()
{
int x = 0;
int cnt = resultList.Count;
isCanceled = false;
DeleteThreadHandler("beginprogress");
try
{
DeleteThreadHandler("begindelete");
for (int j = 0; j < cnt; j++)
{
if (resultList[x].isChecked)
{
DeleteThreadHandler("progress");
DeleteFile(resultList[x].name, deleteForm.isDeletePermanently);
if (File.Exists(resultList[x].name))
{
DeleteErrorHandler(resultList[x].name);
isError = true;
}
else
resultList.RemoveAt(x);
}
else
++x;
if (isCanceled)
break;
}
}
finally
{
validity(true);
DeleteThreadHandler("enddelete");
}
}
void DeleteErrorHandler(string val)
{
Action action = null;
action = () =>
{
errorReportForm.AddError(val);
};
this.BeginInvoke(action);
}
void DeleteThreadHandler(String title)
{
Action action = null;
if (title == "beginprogress")
{
action = () =>
{
};
}
else
if (title == "begindelete")
{
action = () =>
{
olvVirtual.BeginUpdate();
};
}
else
if (title == "enddelete")
{
action = () =>
{
olvVirtual.VirtualListSize = resultList.Count;
olvVirtual.EndUpdate();
RefreshStatus();
progressForm.Close();
if (isError)
errorReportForm.ShowDialog();
};
}
if (title == "progress")
{
action = () =>
{
progressForm.IncProgress(1);
};
}
this.BeginInvoke(action);
}
private void DeleteBtn_Click(object sender, EventArgs e)
{
int checkedcount = GetCheckedCount();
if (checkedcount == 0)
{
MessageBox.Show("Please mark at least a file first");
return;
}
DialogResult dr = new DialogResult();
if (deleteForm == null)
deleteForm = new DeleteForm();
dr = deleteForm.ShowDialog();
if (dr == DialogResult.OK)
{
//if (progressForm == null)
progressForm = new ProgressForm(this);
progressForm.Text = "Deleting...";
progressForm.SetMax(checkedcount);
if (errorReportForm == null)
errorReportForm = new ErrorReportForm();
errorReportForm.ClearMemo();
isError = false;
Thread t = new Thread(DeleteFiles);
t.Start();
progressForm.ShowDialog();
}
}
在 progressForm 中,有一个进度条和计时器,每 500 毫秒更新一次进度。问题是我仍然可以访问主表单,我也尝试了 BeginInvoke 但都不起作用有人知道出了什么问题吗?
谢谢
编辑:我找到了这个混乱的来源,它是使用 Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile 的 DeleteFile。用非托管代码替换它后,它工作正常。