Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing Parent without closing child

I have a project where a setup dialog (Parent) pops. When the user hit continue a main dialog is opened (Child). From within the main dialog the user can re-edit the setup dialog (Parent). When the user clicks on X to close the setup dialog, the application terminates. I assume this is because we close the Parent and it disposes all its children

Is it possible to close the Parent (or hide it) without closing the main dialog (child)? If not would the following fix would work? Open the Main Dialog as Parent and make it open the setup dialog (Child)

like image 260
user1656557 Avatar asked Feb 20 '23 05:02

user1656557


1 Answers

In the Program.cs file, you probably have a function like this:

    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

This function is the entry point for your application. The Application.Run() function runs the main loop of the application. The main loop of a graphical application is the place where the event handler triggers the events, the UI gets updated and so on. If an event (for example pressing a button) takes too long to process, the UI hangs. To prevent this from happening, one can use threading.

The Application.Run() function is overloaded, so if the function has a parameter (new Form1() in this case), the form becomes the 'main' form, so the main loop will exit when the form is closed.

To fix this issue, you need to remove the parameter, which will make the main loop run without closing when the form closes:

    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run();
    }

However, this creates 2 problems:

  1. No form is displayed at start-up, because we removed that from the Main function. To fix this, you need to create a new form in the main function, and show it:

    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
    
        Form1 form = new Form1();
        form.Show();
    
        Application.Run();
    }
    
  2. The application will not exit when you close the form. If you close all forms, the process will be still running, so you need to call Application.Exit(); when you want the application to exit (e.g. form closing event).

like image 125
Tibi Avatar answered Feb 27 '23 14:02

Tibi