Skip to content

Commit

Permalink
Properly cancel and close all open forms when main form closes
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexxEG committed Aug 22, 2021
1 parent 6dc4e42 commit b7dc1ab
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
20 changes: 18 additions & 2 deletions BSA Browser/BSABrowser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -297,10 +297,13 @@ private void ShowProgressForm_Click(object sender, EventArgs e)

BackgroundWorker bw = new BackgroundWorker();
bw.WorkerReportsProgress = true;
bw.DoWork += delegate
bw.DoWork += delegate (object _, DoWorkEventArgs eventArgs)
{
for (int i = 0; i < 10; i++)
{
if (eventArgs.Cancel)
break;

decimal percentage = (decimal)i / 10 * 100;
bw.ReportProgress((int)percentage);
System.Threading.Thread.Sleep(1000);
Expand All @@ -315,6 +318,12 @@ private void ShowProgressForm_Click(object sender, EventArgs e)
pf.BlockClose = false;
pf.Close();
};

pf.Canceled += delegate
{
bw.CancelAsync();
};

bw.RunWorkerAsync();
}

Expand Down Expand Up @@ -365,7 +374,14 @@ private void BSABrowser_Load(object sender, EventArgs e)
private void BSABrowser_FormClosed(object sender, FormClosedEventArgs e)
{
// Signal to close all Forms when MainForm closes
Application.Exit();
for (int i = Application.OpenForms.Count; i-- > 0;)
{
Form form = Application.OpenForms[i];
if (form is ProgressForm)
(form as ProgressForm).ForceCancel();
else
form.Close();
}
}

private void BSABrowser_FormClosing(object sender, FormClosingEventArgs e)
Expand Down
10 changes: 10 additions & 0 deletions BSA Browser/ProgressForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,5 +124,15 @@ private void OnCanceled(EventArgs e)
{
Canceled?.Invoke(this, e);
}

/// <summary>
/// Cancels and closes <see cref="ProgressForm"/>.
/// </summary>
public void ForceCancel()
{
OnCanceled(EventArgs.Empty);
this.BlockClose = false;
this.Close();
}
}
}

0 comments on commit b7dc1ab

Please sign in to comment.