Is there a way to know when the game is been played or if it on the background?

I really need it right now, There are some functionalities in my game that are influenced by the Alt key press and release. And when the user is using the Alt key for switching windows, the Alt key will receive the press event but not the released event, and the pressed state will stay on when the user is getting back to the game and it won’t stop until the user press and release Alt again.
Is there any solution to this problem?