Home > Backend Development > C++ > How to Keep a Windows Forms Application Running After Closing the Startup Form?

How to Keep a Windows Forms Application Running After Closing the Startup Form?

Linda Hamilton
Release: 2025-01-29 10:33:10
Original
246 people have browsed it

How to Keep a Windows Forms Application Running After Closing the Startup Form?

The application is stopped to terminate when the starting window is closed

Question: The processing of the window closes the event to prevent the application from terminating

In the absence of multiple windows, the starting window (Form1) is closed when another window (Form2) is displayed. The goal is to keep the application run even after closing Form1.

Answer:

The problem is the default behavior of the main application thread. This thread is usually terminated when the start (program.cs) is closed. To solve this problem:

Modify the code in Program.cs to monitor the closing event of the window:

  1. Implement the FormClosed event processing program:
<code class="language-csharp">[STAThread]
static void Main() {
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    var main = new Form1();
    main.FormClosed += new FormClosedEventHandler(FormClosed);
    main.Show();
    Application.Run();
}</code>
Copy after login
  1. This code guarantees:
<code class="language-csharp">static void FormClosed(object sender, FormClosedEventArgs e) {
    ((Form)sender).FormClosed -= FormClosed;
    if (Application.OpenForms.Count == 0) Application.ExitThread();
    else Application.OpenForms[0].FormClosed += FormClosed;
}</code>
Copy after login
When closing Form1, it will remove the FormClosed event processing program and attach the event to the next open window.

If there are no more open windows, the application is terminated.
  • Otherwise, the event processing program will continue to monitor the closing of the event to ensure that the application will exit only after all the windows are closed.
  • Through these modifications, the application will be operated even after the Form1 is turned off, and the subsequent window will continue to work as expected.

The above is the detailed content of How to Keep a Windows Forms Application Running After Closing the Startup Form?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template