How to Check if Window Has Focus in Gamemaker Studio 2?

Question: Is is possible to detect when someone has clicked off the game window in Gamemaker Studio 2?


Absolutely! Gamemaker makes it super easy. Use the Gamemaker function window_has_focus().

For example, the following code will set the variable ‘clickPlease’ to ‘true’ if the window has focus, and set the variable to ‘false’ if it doesn’t.

  // Window is not in focus
  clickPlease = 1;
  // Window is in focus
  clickPlease = 0;

If you want to check when someone has clicked of the window, it will be a little bit more complicated. You would have to check if window has had focus last frame, and compare it with if it has focus this frame.

The following code will show a message when the window loses focus:

End step event:

windowHasFocusLast = window_has_focus();

Step event:

if(windowHasFocusLast) and (!window_has_focus(())
	// Window had focus last frame, but lost focus this frame
	show_message("The window is no longer in focus. :(");

About The Author

Mike Miller
Mike Miller Since the age of nine, Mike Miller has been coding his own games, visualizations, and other technological projects.