OBS should do exactly what you need. It's designed for streaming but it also works for screen-recording and can be set to record a specific window which, if i recall correctly, will mean that it can record a window even if it is being covered by/is behind other windows or applications.
Also for anyone else who is interested, OBS also has a "replay recording" feature where, instead of recording a full gameplay session (or whatever) and editing it down to "the good parts" after, you can set it up such that OBS will just be recording to memory in the background and whevever you click the "save replay" button, OBS will save the last 20-seconds or so (duration depends on how much memory you allow OBS to use for this) as a video clip in a configured location. This often used by streamers to save particularly awesome moments of gameplay moments after they happen, but it will also work for anything you plan to record using OBS.
Oh and it's open source and allows you to specify varying combinations of inputs and outputs like you specify in your question, as this overlaying and combining different inputs is something streamers do quite often (like putting their webcam feed in the corner, picture in picture style, so viewers can see them and the gameplay)