0

Is there a way to invoke (by code) the click event of the "x" on the top right corner of a Form? To be "as if" a user clicked on that?

Ps. I don't want a function that does this.Close()

I read the other answer, but It seems that Application.Exit(); Application.ExitThread(); Environment.Exit(); aren't showing a different behaviour.

In particular, my application works like this:

Main
{
    using (Form1 f = new Form())
    {
        f.Show();
    }

    using(Game1 game = new Game1())
    {
        // Create game
        game.Run(); //Xna Framework
    }
    // Do something
}

Note that I don't see the code of Run() because it is inside the Xna Framework.

Ok, inside my game, in a function I want to exit from it letting Run() to return.

If I do:

this.Exit(); // Game.Exit()

Or the other three possibilities above, the Whole application closes and //Do something isn't executed.

BUT, if I press the "x" on the window of the game, it works.

I can't understand why and I can't understand how to reproduce the "x" click programmatically.

Francesco Bonizzi
  • 5,142
  • 6
  • 49
  • 88
  • What's wrong with `this.Close()`? – Enigmativity Apr 22 '15 at 12:24
  • @Enigmativity It has the same effect than doing this.Exit() – Francesco Bonizzi Apr 22 '15 at 12:40
  • Are you just wanting to close the form without closing the application? – Enigmativity Apr 22 '15 at 12:41
  • You can't close the form without closing the application. The form holds open the message loop. When you close the form the message loop closes and so too does the application. You need to create a second form if you want to be able to close it. – Enigmativity Apr 22 '15 at 23:15
  • @Enigmativity I have a static main in which other forms are created, abd when I close them they Return as expected, they don't let the whole Application shut down. – Francesco Bonizzi Apr 23 '15 at 09:17
  • Yes, that's what is expected. The "root" form, if you want to think of it that way, holds the app open. Child forms do not. You can close as many child forms as you like, but close the "root" form and the app closes. – Enigmativity Apr 23 '15 at 09:32
  • I don't know if I understood correctly your answer, but I want to say that I don't call the .Run() from the "form"! I call it inside static main in Program.cs – Francesco Bonizzi Apr 23 '15 at 10:13

1 Answers1

-1

You could send the WM_CLOSE message to your window handle. This would involve using native winapi calls.

See: send message to a window handle

Community
  • 1
  • 1
Andrei Tătar
  • 7,872
  • 19
  • 37