-1

I have application of two forms (just created by AddNewForm)

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
        Application.Run(new Form2());
    }

When Form1 is closed by red cross in top-right corner Form2 is shown as expected.

When Form1 is closed by context menu "Close" shown on form icon in taskbar, application terminates almost immediately. In case Form2 is not shown following happens - its Load eventhandlers are processed, but its FormClosed eventhandlers are not called.

I observe this behavior only on Windows 10 (unable to simulate on Windows 7) and in approx. 80% cases. Any reason WHY?

user2126375
  • 1,594
  • 12
  • 29
  • Hmm, surely you misinterpret what is going on. Once the first Application.Run() completes, your app no longer has any window that can receive the focus. So the OS is forced to find another one, it will belong to a different app. Pretty decent odds that the second window you create will now be *underneath* that other window. It only looks like the app terminated. You are doing it wrong, you'll have to stop doing it wrong. Show Form2 *before* you let Form1 close. Use [this code](http://stackoverflow.com/a/10769349/17034). – Hans Passant Sep 25 '15 at 14:30
  • Hello, process really terminates. Form2 is not underneath other window. – user2126375 Sep 25 '15 at 14:54
  • http://stackoverflow.com/help/mcve – Hans Passant Sep 25 '15 at 14:58
  • Does your "Close" handler kill the application or does it call Form1.Close()? – Tom Sep 25 '15 at 21:11
  • Close and Load handlers are empty. I am just checking inside if handlers was called (thus I can say that Closed handler of Form2 was not called) – user2126375 Sep 26 '15 at 05:00

1 Answers1

0

If I replace Application.Run(new FormXX()) by new FormXX().ShowDialog() application starts behaving as expected. So there will be some issue in Application.Run related to multiple call of this method in one thread.

My current solution is based on running Application.Run() only one time per thread. Following code never ends up closing Form2 immediately:

Thread thread1 = new Thread(() =>
{
    Application.Run(new Form1());
});
thread1.SetApartmentState(ApartmentState.STA);
thread1.Start();
thread1.Join();

Thread thread2 = new Thread(() =>
{
    Application.Run(new Form2());
});
thread2.SetApartmentState(ApartmentState.STA);
thread2.Start();
thread2.Join();
user2126375
  • 1,594
  • 12
  • 29