5

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!

PowerUser
  • 812
  • 1
  • 11
  • 32

1 Answers1

5

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.

libertylocked
  • 892
  • 5
  • 15
  • 1
    Can you give some remarks on why I should only pause `Update()`? I mean it does work only if I check in `Update()` but why shouldn't I check for this in `Draw()` as well? – PowerUser Mar 17 '16 at 21:15
  • 2
    If your `Draw()` code is strictly drawing stuff, then it won't change the state of the game, therefore does not need to be paused – libertylocked Mar 17 '16 at 21:21
  • 1
    FWIW, It is much "friendlier" for a game to also stop Drawing, when not foreground, as that is what consumes the most cpu cycles (and battery life, on a mobile device). Or to greatly reduce its frame rate. (And stop drawing completely when Minimized.) Two words: "Max-Q laptop". Even a high-end game can't assume any more that no one would try to run it on a laptop without being plugged in. – ToolmakerSteve Mar 22 '18 at 23:36