代码功能:toolStripProgressBar进度条完成的时候,打开OpenFileDialog (打开文件对话框);进度条由Timer控制。
如代码所示,如果标识符isOperate的赋值放在ShowDialog()方法后面会导致OpenFileDialog的多次打开。(怀疑是ShowDialog执行过程中继续触发timer1_Tick()导致的)
方法1:把标识符isOperate的赋值放前面就正常,只打开一次
bool isOperate = false;
private void timer1_Tick(object sender, EventArgs e)
{
if (toolStripProgressBar1.Value < toolStripProgressBar1.Maximum)
{
this.toolStripProgressBar1.PerformStep();//增加进度条进度
}
if (toolStripProgressBar1.Value >= toolStripProgressBar1.Maximum) {
if (!isOperate)
{
isOperate = true;
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog1.InitialDirectory = "d:\\app\\";
openFileDialog1.Filter = ("bmp文件(*.bmp)|*.bmp|exe文件(*.exe)|*.exe");
openFileDialog1.ShowDialog();
//isOperate = true;//放ShowDialog()后面会导致多次执行
}
timer1.Enabled = false;
}
}
方法2:用线程执行ShowDialog()方法
bool isOperate = false;
private void timer1_Tick(object sender, EventArgs e)
{
if (toolStripProgressBar1.Value < toolStripProgressBar1.Maximum)
{
this.toolStripProgressBar1.PerformStep();//增加进度条进度
}
if (toolStripProgressBar1.Value >= toolStripProgressBar1.Maximum) {
if (!isOperate)
{
//isOperate = true;//changed
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog1.InitialDirectory = "d:\\app\\";
openFileDialog1.Filter = ("bmp文件(*.bmp)|*.bmp|exe文件(*.exe)|*.exe");
Thread invokeThread = new Thread(new ThreadStart(showUI));//changed
invokeThread.SetApartmentState(ApartmentState.STA);//changed
invokeThread.Start();//用线程可以解决
isOperate = true;//changed
}
timer1.Enabled = false;
}
}
void showUI() { //changed
openFileDialog1.ShowDialog();
}