Closing a parent without closing a child

I have a project in which the installation dialog (Parent) appears. When the user clicks the button, the main dialog box (Child) opens. In the main dialog box, the user can re-edit the settings dialog box (Parent). When the user clicks on X to close the installation dialog, the application terminates. I suppose this is because we close the parent and have all its children

Is it possible to close the parent (or hide it) without closing the main dialog box (child)? If the following fix were not fixed? Open the main dialog as a parent and run the settings dialog (Child)

+4
source share
2 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 feature is the entry point for your application. The Application.Run() function starts the main application loop. The main loop of a graphical application is where the event handler fires events, the user interface is updated, and so on. If an event (such as a button click) takes too much time to process, the user interface freezes. To prevent this from happening, you can use threads.

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 problem, you need to remove the parameter that will make the main loop work without closing when the form closes:

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

However, this creates 2 problems:

  • When you start the form is not displayed, because we removed it 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(); } 
  • The application will not exit when you close the form. If you close all forms, the process will still be running, so you need to call Application.Exit(); when you want the application to exit (for example, a form closing event).

+8
source

Or you simply cannot understand that a modal window cannot live without a parent. When the parent is minimized, all modal forms become hidden. When a parent closes, the same thing happens with modal forms.

So, it’s a bad practice to trick the model form to stay alive after the death of the parent. Just try to save the template in which your second form is another equal form than the first.

0
source

Source: https://habr.com/ru/post/1433120/


All Articles