Cursor lock not working after alt tab

Hi,

I am locking cursor in my game like this:

if (value)
{
      Cursor.lockState = CursorLockMode.Confined;
}
else
{
     Cursor.lockState = CursorLockMode.None;
}

And it works fine, prevents mouse from going to my second monitor and i can disable the lock at any time in options. But when I alt-tab or just when app loses focus, then the cursor lock doesn’t work after coming back to the app. Even setting lock again in the options doesn’t help.

Would really appreciate help with this problem and thanks for your help in advance!

“Found out the problem was being caused by the “Run in background*” player setting being disabled. Enabling it has fixed the problem!”
-from Reddit - Dive into anything

The answer : https://docs.unity3d.com/Manual/class-PlayerSettingsStandalone.html
@Zeriver

try using Unity - Scripting API: Application.isFocused as your bool check. if the application is focused, lock cursor, else dont