Cadybrille
Cadybrille

Reputation: 31

Check Controller Connection with SDL2?

So I want to check if a controller is still connected after properly initialization with this

    joystick_ = SDL_JoystickOpen(0);
    if (!joystick_) {
        std::cerr << "Failed to open joystick: " << SDL_GetError() << std::endl;
        SDL_Quit();
        exit(1);
    }

is there a way to check the connection of controller in real time in SDL2?

so far I have tried

while (SDL_PollEvent(&e)) {
   ...
   else if (e.type == SDL_JOYDEVICEREMOVED) {...}
}

or

SDL_JoystickID instance_id = SDL_JoystickInstanceID(joystick_);

    bool controllerIsConnected = false;

    // Check all available joystick devices
    for (int i = 0; i < SDL_NumJoysticks(); ++i) {
        // If the instance ID of the opened joystick matches the instance ID of any connected joystick, it's still connected
        if (instance_id == SDL_JoystickGetDeviceInstanceID(i)) {
            controllerIsConnected = true;
            break;
        }
    }

and even

bool controllerIsConnected = (bool)SDL_JoystickOpen(0);

Nothing works so far in the case where I simply turn off bluetooth function of the computer

Upvotes: 3

Views: 431

Answers (0)

Related Questions