Skip to content

Instantly share code, notes, and snippets.

@MatthewKing
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MatthewKing/6bad45fc9af5e040cc4b to your computer and use it in GitHub Desktop.
Save MatthewKing/6bad45fc9af5e040cc4b to your computer and use it in GitHub Desktop.
Extension methods adding an awaitable ShowAsync method to System.Windows.Forms.Form.
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
/// <summary>
/// Extension methods for System.Windows.Forms.Form.
/// </summary>
static class FormExtensions
{
/// <summary>
/// Shows the form to the user.
/// </summary>
/// <param name="form">
/// The form to show.
/// </param>
/// <returns>
/// A task representing the asynchronous operation.
/// </returns>
public static Task<DialogResult> ShowAsync(this Form form)
{
return ShowAsync(form, () => form.Show());
}
/// <summary>
/// Shows the form with the specified owner to the user.
/// </summary>
/// <param name="form">
/// The form to show.
/// </param>
/// <param name="owner">
/// Any object that implements System.Windows.Forms.IWin32Window and represents
/// the top-level window that will own the form.
/// </param>
/// <returns>
/// A task representing the asynchronous operation.
/// </returns>
public static Task<DialogResult> ShowAsync(this Form form, IWin32Window owner)
{
return ShowAsync(form, () => form.Show(owner));
}
/// <summary>
/// The internal ShowAsync implementation.
/// </summary>
/// <param name="form">
/// The form to show.
/// </param>
/// <param name="show">
/// The action that shows the form.
/// </param>
/// <returns>
/// A task representing the asynchronous operation.
/// </returns>
private static Task<DialogResult> ShowAsync(Form form, Action show)
{
TaskCompletionSource<DialogResult> tcs = new TaskCompletionSource<DialogResult>();
FormClosingEventHandler handler = null;
handler = new FormClosingEventHandler((s, e) =>
{
form.FormClosing -= handler;
tcs.SetResult(form.DialogResult);
});
form.FormClosing += handler;
show();
return tcs.Task;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment