Question

I have some problems with windows focus in SDL2.

I got two windows and listen to focus gain and lost events.

When I click on Window 2, the following events trigger:

"Window 1 lost focus"
"Window 2 gained focus."

When I click on Window 1, the following events trigger:

"Window 2 lost focus."
"Window 1 gained focus."
"Window 1 lost focus."

I can clearly tell the window has focus by the glowing effect my operating system draws around it.
Also, other SDL2 functions to get focus information give the same, wrong, answer when tested on Window 1.

I trimmed down the code to an almost-minimal test case:

#include <iostream>
#include <SDL2/SDL.h>
using namespace std;
int main(int argc, char **argv) {
  SDL_Init(SDL_INIT_VIDEO);
  SDL_Window* w1=SDL_CreateWindow("Window 1",
                                  SDL_WINDOWPOS_UNDEFINED,
                                  SDL_WINDOWPOS_UNDEFINED,
                                  250,200,SDL_WINDOW_SHOWN);
  SDL_Window* w2=SDL_CreateWindow("Window 2",
                                  SDL_WINDOWPOS_UNDEFINED,
                                  SDL_WINDOWPOS_UNDEFINED,
                                  200,250,SDL_WINDOW_SHOWN);
  bool quit=false;
  while(!quit){
    SDL_Event e;
    while(!quit && SDL_PollEvent(&e)){
      switch(e.type){
        case SDL_WINDOWEVENT :
          { // this block just scopes 'targetWindow' and 'title'
            SDL_Window* targetWindow=SDL_GetWindowFromID(e.window.windowID);
            const char* title=SDL_GetWindowTitle(targetWindow);
            switch(e.window.event){
              case SDL_WINDOWEVENT_FOCUS_GAINED :
                // tell which window gained focus
                cout << title << " gained focus!" << endl;
                break;
              case SDL_WINDOWEVENT_FOCUS_LOST :
                // tell which window lost focus
                cout << title << " lost focus!" << endl;
                break;
            }
          }
          break;
        case SDL_QUIT :
          quit=true;
          break;
      }
    }
  }
  SDL_Quit();
  return 0;
}

Is this a bug in SDL2 multi-windows support? Does it depend on the underlying windowing system?

More importantly, is there a way to have correct focus information for multiple windows with SDL2?

Thanks in advance for your help.

Was it helpful?

Solution

I did a little more research on this and find out that the issue I described is a known bug as can be seen here.

There's a patch at the other end of the link but that's already included in the latest version of SDL.

Personally, I solved this by installing version 2.0.3 of the library.

Hope this will help someone else.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top