Yeah I can't say as this is something I've ever actually done. I've always got a keyboard nearby, whether on my PC or streaming to my Steam Link, so I've never needed to do this. It should be possible though.
In order to do this on a game by game basis you'll probably need to use the Additional Application feature. You can right-click on a game in your library, go to Edit, and then go to the Additional Application tab and select "Add Application...". Here you could direct it to an AHK script that will change the buttons as needed, and then check the "Automatically Run Before Main Application Box". This will make the script (or whatever else you add as an application) run just before starting the game/emulator. You could then add another Additional Application that would close/unload the script you started and tell it to "Automatically Run After Main Application".
This is predicated on you knowing how to actually write the scripts you need, but it sounds like you already know how to do that.