Hi,
To me this sounds like you need to dynamically create a palette that suits both the background and *each* window (not just one window); or have a predefined/standard palette that everything must use; or make everything dynamically allocate palette entries.
The first option will give you the best quality results. In this case, for each frame you'd calculate the best palette possible, then find the closest available colour for each pixel (based on it's original/desired colour). Of course this is complex and has a very high overhead.
For the last option, different pieces of software try to allocate certain ranges of palette entries. For example, the code that draws the background wallpaper might ask for 32 palette entries (and might only get 10 palette entries because not enough are free), and then it needs to figure out how to use the palette entries to get the best results. This is complex and the results won't be as good as the first option. The advantage here is that you don't need to recalculate everything for each frame (much less overhead than the first option). In this case you'd probably also want to define a certain range as standard colours. For example, use the first 16 palette entries for standard CGA colours (black, blue, cyan, green, red, ..., light magenta, yellow, white) so that all software can use these colours in addition to any extra palette entries that have been allocated.
For 8-bpp modes I use the second option. I define the palette as "3r:3g:2b"; so that there's 8 shades of red, 8 shades of green and 4 shades of blue (where any pixel can be any combination of these shades); and so that it can be used like 15-bpp ("5r:5g:5b") or 16-bpp ("5r:6g:5b") or 24/32-bpp ("8r:8g:8b") where no code needs to care about the palette at all. This makes things a lot easier but the choice of possible colours (and therefore the quality of the resulting pictures) is worse because of it. The way I see it is that if people wanted a good range of colours they'd be using 32-bpp anyway...
Cheers,
Brendan