DialogResult button has not been (re) installed?

In my Windows Forms application, I have a child form that runs as modal on my main form. The detailed form acts as a wizard for a long-term task and contains a Cancel button. In the designer, I have this undo button DialogResult

set to DialogResult.Cancel

. However, if the user resists clicking the Cancel button until the long-running operation is complete, the Cancel button text will change to Close. I would like the button DialogResult

to DialogResult.None

be there if this happens.

Unfortunately, the setting is not saved. To maintain a responsive user interface, the long-term task is executed in a separate Task

, and then the update of the user interface after the task completes is performed in the block ContinueWith

after that, which in turn uses Invoke

Work to execute the user interface. It looks something like this:

Task.Factory.StartNew(() =>
{
    MyStaticClass.DoLotsOfWork(a, b, myCancellationToken);
    return MyStaticClass.TellMeAboutIt(a, c, myCancellationToken);
}, myCancellationToken)
.ContinueWith(task =>
{
    switch(task.Status)
    {
    case TaskStatus.RanToCompletion:
        Invoke((MethodInvoker)delegate
        {
            cancelButton.Text = "Close";
            cancelButton.DialogResult = DialogResult.None;
            // other UI-related stuff.
        }
    // Other cases here...
    }
});

      

When I run the code, the text gets Close, no problem. It seems to DialogResult

change: if I go through the debugger, the debugger tells me that the value has changed. However, when the window is closed (using the cancel / close button) DialogResult

, the returned myWindow.ShowDialog()

is always DialogResult.Cancel

.

This is mistake? Am I doing something wrong? Can a person not install DialogResult

buttons programmatically "on the fly"?

+3


source to share


1 answer


There are several reasons why DialogResult will be set to Cancel. For example, you can make a mistake by calling Close () on the Click event handler button. This closes the window, but since the DialogResult was never assigned, Winforms should accept Cancel. Hiding the window is another way to trigger this, the window cannot remain modal when you make it invisible. It is imperative that all other windows are disabled, and the last remaining one is hidden, the user will no longer be able to return to the program.

An ominous way to deal with the state of a dialog is to ever set the DialogResult property. As soon as you change it from None to something else, Winforms will close the dialog and the result of the dialog will be unambiguous. Therefore, consider removing the Click event handler and changing the code to:



case TaskStatus.RanToCompletion:
    Invoke((MethodInvoker)delegate
    {
        cancelButton.Text = "Close";
        cancelButton.DialogResult = DialogResult.OK;
    }

      

+5


source







All Articles