SFML / SFML

Simple and Fast Multimedia Library
https://www.sfml-dev.org/
zlib License
10.19k stars 1.72k forks source link

GainedFocus does not trigger if window has no focus at launch #1286

Open naezith opened 7 years ago

naezith commented 7 years ago

I start the game and click away before window opens. Game checks window.hasFocus() and sets focus to false. (Red color) Then I click to the game window 50 times but game does not get any sf::Event::GainedFocus.

It triggers sf::Event::GainedFocus only if I click away again and click to game again.

If I remove the window.hasFocus(), game starts and gets all the inputs even if it's in not focused, it's in background. So I coded a workaround for my game for now, which is to poll window.hasFocus() for a while at start, not an elegant solution.

Windows 10 SFML 2.4.2 gcc (x86_64-posix-seh-rev1, Built by MinGW-W64 project) 6.3.0

#include <iostream>
#include <SFML/Graphics.hpp>

int main() {
    sf::RenderWindow window;
    window.create(sf::VideoMode(800, 600), "Focus Test", sf::Style::Default);

    // Set to red if window has no focus at launch
    sf::Color color = window.hasFocus() ? sf::Color::Green : sf::Color::Red;

    while(window.isOpen()) {
        sf::Event event;
        while(window.pollEvent(event)) {
            if(event.type == sf::Event::Closed)  window.close();
            else if(event.type == sf::Event::GainedFocus) color = sf::Color::Green;
            else if(event.type == sf::Event::LostFocus) color = sf::Color::Red;
        }

        window.clear(color);
        window.display();
    }

    return 0;
}
MarioLiebisch commented 7 years ago

I don't remember it specifically, but I'm pretty sure this was a case of simply "we don't know", because Windows won't trigger the event to begin with (so it's basically a glitch in the window manager). It's something I've seen in many AAA games as well. If you launch the game and switch programs immediately, Windows won't grant it focus but the game will act as if it does. I could be wrong and/or this could have changed, if anyone wants to dig a bit.