David Bentley
David Bentley

Reputation: 864

ShowDialog() is not preventing the originating form from being clickable

I have a winform with the following code that opens an external program when the form is opened. If the program closes, a dialog box is suppose to pop up with an option to return that a button was clicked. This will close the dialog box and return to the initial form and then run the function to open the external program again.

Here is the problem, the original form is STILL clickable AND the function is not running. Any ideas?

    public Manager()
    {
        InitializeComponent();
        ExternalProgramOpen();

    }

    private void ExternalProgramOpen()
    {
        Process startProgram = Process.Start("program.exe", Program.ConnectionArg);
        startProgram.EnableRaisingEvents = true;
        startProgram.Exited += this.PrematureClose;
    }

    private void PrematureClose(object sender, EventArgs e)
    {
        ManagerWarning messagepopup = new ManagerWarning();
        messagepopup.ShowDialog();
        using (var ManagerWarning = new ManagerWarning())
        {
            if (ManagerWarning.ShowDialog() == DialogResult.Retry)
            {
                ExternalProgramOpen();
            }
        }
     }

Upvotes: 0

Views: 410

Answers (1)

René Vogt
René Vogt

Reputation: 43936

The reason for this effect is probably that the Exited event is not raised in the same UI thread that started the process.

When you call ShowDialog() from another thread, the new window will not use and block the original UI thread.

To solve this, check if InvokeRequired is true and use Invoke:

private void PrematureClose(object sender, EventArgs e)
{
    if (InvokeRequired)
    {
        Invoke(new Action(() => PrematureClose(sender, e)));
        return;
    }

    // your code here
    // ...
}

Upvotes: 2

Related Questions