We are currently migrating Bugzilla to GitHub issues.
Any changes made to the bug tracker now will be lost, so please do not post new bugs or make changes to them.
When we're done, all bug URLs will redirect to their equivalent location on the new bug tracker.

Bug 2548

Summary: Cannot poll joystick button when window is not in focus
Product: SDL Reporter: Alan <aychen>
Component: joystickAssignee: Ryan C. Gordon <icculus>
Status: RESOLVED FIXED QA Contact: Sam Lantinga <slouken>
Severity: normal    
Priority: P2 CC: aychen, icculus
Version: 2.0.3   
Hardware: x86   
OS: Mac OS X 10.8   

Description Alan 2014-05-16 20:07:32 UTC
I'm running an interface that uses both joysticks and keyboard.  

For the joysticks, I'm polling the axes, hats, and buttons.  I use SDL_JoystickEventState(SDL_DISABLE) to turn off the joystick events and then I run SDL_JoystickUpdate() to poll the joystick values. 

For the keyboard, I'm using SDL_PollEvent(&event) to search for keystroke events after I've created a window.  

What I've noticed is that when the window is not in focus, the buttons for the joystick no longer work.  The hat and axes still work.  Oddly enough, if I don't ever call SDL_PollEvent, then the joystick button works when the window is not in focus. 

Thank you,
Alan
Comment 1 Ryan C. Gordon 2014-05-19 00:50:53 UTC
(In reply to Alan from comment #0)
> What I've noticed is that when the window is not in focus, the buttons for
> the joystick no longer work.  The hat and axes still work.  Oddly enough, if
> I don't ever call SDL_PollEvent, then the joystick button works when the
> window is not in focus. 

Not giving joystick events when an SDL window doesn't have focus is intentional (although I would argue incorrect) behavior.

Never calling SDL_PollEvent() "works" because SDL doesn't know the window lost focus until the OS event queue is processed, which happens under SDL_PollEvent(), even if the OS has already taken focus from the window.

I'm surprised you get hat and axes events, though; they should be protected by the same check as the buttons.

Anyhow, to get joystick events even if the window doesn't have focus, call this sometime after SDL_Init()...

    SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1");

(That probably fixes your concern, but I'm marking this bug ASSIGNED for now, so I can see why the hats and axes still come through.)

--ryan.
Comment 2 Alan 2014-05-19 16:22:22 UTC
Hey Ryan, 

That worked great, thank you. 

Alan
Comment 3 Sam Lantinga 2014-06-22 04:31:41 UTC
I fixed the bug where you got axis and hat events if the application didn't have focus.
https://hg.libsdl.org/SDL/rev/8e09eceea61e