Search code examples
c#xnamonogame

C# Monogame - How to stop game loop while the game window is minimized


I have a fullscreen Windows game that I'm working on. And today I saw an indie game (made in XNA) have the following behavior: when it is the focused window it will Update() and Draw() but when it gets minimized it stops both of these and waits for the user to make it the top window again. Essentially I'm looking for a way to kind of "pause" the entire game loop while the game window is minimized and "resume" it from where it stopped when the game gets focused again. This would mean that if I minimize my game and open my browser, for instance, when I left click, the game GUI logic wouldn't register that and open a window or whatever. Thanks in advance!


Solution

  • Two ways you can do it.

    Method 1: Use Game.IsActive

    IsActive will be false if the game does not have focus... or minimized. So you can do something in the Update loop of your Game1.cs like

    if (this.IsActive) 
    {
        // update your game components
    }
    

    Method 2: Subscribe to Game.Activated and Game.Deactivated events.

    Whenever game loses focus, Deactivated event will be raised. There you can write some code to pause everything. If you have a pause menu, this is a great place to launch the pause menu. Whenever game gains focus, Activated event will be raised. You write some code to unpause your game.

    Either way, you only need to pause your update, not draw. If look at Draw(), it clears the backbuffer and re-draws everything every frame. If Draw() is paused, your game will appear frozen. Draw() should not change the state of the game.