To detect Super Game Boy, the values of SGB Flag and Old Licensee Code must be set in the cartridge header. In detail, that would mean that the value of $0146 is $03 and the value of $014B is $33.
To detect Game Boy Color, use the value of the CGB Flag in the cartridge header. If the value of $0143 is $80, then the game should be compatible with both normal and color Game Boy models. If it is $C0, then it should only work with Game Boy Color.
Additionally, some games check the value of the Accumulator directly after startup. If the value is $01, then the hardware is either Super Game Boy or normal Game Boy. If it is $FF, then the hardware is either Super Game Boy 2 or Game Boy Pocket. If it is $11, then it is either Game Boy Color or Game Boy Advance.
Lastly, you can detect if the game is on a Game Boy Advance by checking bit 0 of the B register directly after startup. If it is cleared, it is a Game Boy Color. If it is set, it is a Game Boy Advance.
__________
Note: The Super Game Boy 2 was little more than a Super Game Boy with a link cable port in it. Some games do detect this, however, like Tetris DX, which will display a different border for Super Game Boy and Super Game Boy 2.
EDIT:
Here is a list of examples for games which detect seperate combinations of hardware configurations:
Normal only: Tetris
Normal or Super: Pokémon
Normal, Super or Color: Game & Watch Gallery 2, Game & Watch Gallery 3
Normal, Super, Color or Super2: Tetris DX
Color only: Super Mario Bros. DX
Advance: The Legend of Zelda: Oracle of Ages, The Legend of Zelda: Oracle of Seasons