How to know if a user clicks in the close window box

If the user quits the game by clicking on the close box in the upper right hand corner of the app, I need to delete some files. How do I know if a user clicks on the close box?

The problem, of course, is that I can’t find Exit() anywhere in my solution. Any ideas on how to easily see if the user is quitting? I saw one solution to a similar problem but it involved recompiling MonoGame source. I think I’ll pass.

Try this:

xna c# trap and cancel the close window (x) button and Ctrl F4 - Stack Overflow

Yeah, I saw that. But then it threw a ton of errors because of ambiguity with Forms, so I was hoping to avoid that.

There is a system32 method too but you need to import and use the DLL call or something…

If necessary I could do the Forms bit and make a whole lot of code changes… sigh.

override Game.OnExiting?

not sure if it’s called in every circumstance … what a about a catch/finally in main?

You mean here?

using System;

namespace GSBPGEMG
    public static class Program
        static void Main()
            using (var game = new Game1())

Yikes! That almost seems sacrilegious. I thought this was sacred not to be messed with code.

Personally I use the OnExiting Override of the Game Class … it’s called by monogame when the mainloop ends and where monogame does unloading of loaded stuff.

It get’s called when using the game windows close box and it’s called when using Alt+F4, so I guess it’s fine for all cases out there


How would I implement “OnExiting Override?”


Found this:

protected override void OnExiting(Object sender, EventArgs args)
    base.OnExiting(sender, args);

    // Stop the threads
1 Like

You could also do this in the destructor of game1:

    // do whatever