Mouse focus behaves differently in fullscreen mode because the window takes up the entire screen and typically prevents other windows from appearing above it. Here's what you need to know:
When your window is in true fullscreen mode, mouse focus events work differently:
SDL_WINDOWEVENT_ENTER
and SDL_WINDOWEVENT_LEAVE
events won't fire unless you move to another screenHere's how to test for fullscreen state and handle focus accordingly:
#include <SDL.h>
#include <iostream>
#include "Window.h"
void HandleWindowEvent(SDL_WindowEvent& E,
SDL_Window* Window) {
bool IsFullscreen = SDL_GetWindowFlags(Window)
& SDL_WINDOW_FULLSCREEN;
if (E.event == SDL_WINDOWEVENT_ENTER) {
if (!IsFullscreen) {
std::cout << "Window gained mouse focus\n";
}
} else if (E.event == SDL_WINDOWEVENT_LEAVE) {
if (!IsFullscreen) {
std::cout << "Window lost mouse focus\n";
}
}
}
int main(int argc, char** argv) {
SDL_Init(SDL_INIT_VIDEO);
Window GameWindow;
// Toggle fullscreen with F key
SDL_Event E;
while (true) {
while (SDL_PollEvent(&E)) {
if (E.type == SDL_KEYDOWN
&& E.key.keysym.sym == SDLK_f) {
bool IsFullscreen = SDL_GetWindowFlags(
GameWindow.SDLWindow) &
SDL_WINDOW_FULLSCREEN;
SDL_SetWindowFullscreen(
GameWindow.SDLWindow,
IsFullscreen
? 0
: SDL_WINDOW_FULLSCREEN);
} else if (E.type == SDL_WINDOWEVENT) {
HandleWindowEvent(E.window,
GameWindow.SDLWindow);
}
}
GameWindow.Update();
}
SDL_Quit();
return 0;
}
Window gained mouse focus
Window lost mouse focus
If your game supports multiple monitors, you'll need to handle cases where the user moves between screens:
#include <SDL.h>
#include <iostream>
#include "Window.h"
void MonitorMousePosition(SDL_Window* Window) {
int MouseX, MouseY;
SDL_GetGlobalMouseState(&MouseX, &MouseY);
int DisplayIndex{
SDL_GetWindowDisplayIndex(Window)};
SDL_Rect DisplayBounds;
SDL_GetDisplayBounds(DisplayIndex,
&DisplayBounds);
bool MouseOnSameDisplay{
MouseX >= DisplayBounds.x &&
MouseX < DisplayBounds.x + DisplayBounds.w &&
MouseY >= DisplayBounds.y &&
MouseY < DisplayBounds.y + DisplayBounds.h
};
std::cout << "\nMouse on game display: "
<< (MouseOnSameDisplay ? "yes" : "no");
}
int main(int argc, char** argv) {
SDL_Init(SDL_INIT_VIDEO);
Window GameWindow;
SDL_Event E;
while (true) {
while (SDL_PollEvent(&E)) {
if (E.type == SDL_MOUSEMOTION) {
MonitorMousePosition(
GameWindow.SDLWindow);
}
}
GameWindow.Update();
}
SDL_Quit();
return 0;
}
Mouse on game display: no
Mouse on game display: yes
Mouse on game display: yes
Remember that fullscreen behavior can vary between operating systems and even between fullscreen modes (exclusive vs borderless windowed). Always test your focus handling across different configurations.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to track and respond to mouse focus events in SDL2, including handling multiple windows and customizing focus-related click behavior.