I try to achieve this: i have the main form, when user click the red cross on the top right to exit the application, it popup a progress bar form indicating the application is updating/saving information. After the background worker in the progress bar form finishes, it closes the progress bar form and close the main form as well. the problem i have is, it closes the main from first without even running the background worker. how to fix this? i tried to use e.cancel= true it just gave my dead loop.
here is my main form:
private static void mainForm_FormClosing(object sender, FormClosingEventArgs e)
{
UpdatingForm pbar = new UpdatingForm ();
pbar.Show();
}
in my updatingform:
public UpdatingForm()
{
InitializeComponent();
bgWorker.RunWorkerAsync();
}
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
....
}
private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Close();
// Application.Exit();
}
Setting e.Cancel
to true
is correct. However, once your UpdatingForm
closes, Application.Exit()
fires the mainForm_FormClosing()
event again, so you get one more UpdatingForm
etc.
private static bool isClosing = false;
private static void mainForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (!isClosing)
{
isClosing = true;
e.Cancel = true;
UpdatingForm pbar = new UpdatingForm ();
pbar.Show();
}
}
Maybe this code works.test it
private static void mainForm_FormClosing(object sender, FormClosingEventArgs e)
{
UpdatingForm pbar = new UpdatingForm ();
pbar.Show();
while (pbar.Created)
{
Application.DoEvents()
}
}
or
private static void mainForm_FormClosing(object sender, FormClosingEventArgs e)
{
UpdatingForm pbar = new UpdatingForm ();
pbar.Show();
while (! pbar.IsDisposed)
{
Application.DoEvents()
}
}
Have you checked this article
C# BackGroundWorker with ProgressBar Updates after process complete
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.