Winform Show user control as Modal

T.Zacks 3,986 Reputation points
2022-01-24T17:49:54.08+00:00

See the code first which is working. code taken from https://stackoverflow.com/questions/46203551/modal-like-user-control

public partial class DialogControl : UserControl
{
    TaskCompletionSource<DialogResult> _tcs;

    public DialogControl()
    {
        InitializeComponent();
        this.Visible = false;
    }

    public Task<DialogResult> ShowModalAsync()
    {
        _tcs = new TaskCompletionSource<DialogResult>();

        this.Visible = true;
        this.Dock = DockStyle.Fill;
        this.BringToFront();
        return _tcs.Task;
    }

    private void btmCancel_Click(object sender, EventArgs e)
    {
        this.Visible = false;
        _tcs.SetResult(DialogResult.Cancel);
    }

    private void btnOk_Click(object sender, EventArgs e)
    {
        _tcs.SetResult(DialogResult.OK);
        this.Visible = false;
    }

    public string UserName
    {
        get { return txtName.Text; }
        set { txtName.Text = value; }
    }
}


private async void btnShowDialogControl_Click(object sender, EventArgs e)
{
    var control = new DialogControl();
    splitContainer1.Panel2.Controls.Add(control);

    //Disable your other controls here


    if (await control.ShowModalAsync() == DialogResult.OK) //Execution will pause here until the user closes the "dialog" (task completes), just like a modal dialog.
    {
        MessageBox.Show($"Username: {control.UserName}");
    }

    //Re-enable your other controls here.

    splitContainer1.Panel2.Controls.Remove(control);
}

Specially see this code

public Task<DialogResult> ShowModalAsync()
{
    _tcs = new TaskCompletionSource<DialogResult>();

    this.Visible = true;
    this.Dock = DockStyle.Fill;
    this.BringToFront();
    return _tcs.Task;
}

My question is why they return Task<DialogResult> ? they could simply return only ** ** from the function ShowModalAsync()?

if we do not return task then it would not be possible to wait for usercontrol execution pause?

please help me to understand why they return Task<DialogResult> ?

Thanks

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,520 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,286 Reputation points
    2022-01-24T18:15:57.193+00:00

    The reason for returning Task<DialogResult> is because of TaskCompletionSource as without out this the code would be no different than a common call to ShowDialog. The author explains it well The key ingredient is TaskCompletionSource. It represents the "state" of a Task, and lets you "complete" it from another point in code, in this case, a button on the "dialog".

    0 comments No comments

0 additional answers

Sort by: Most helpful