Search code examples
c#windowswinformslockingwindows-screensaver

How can I check Windows Lock settings?


I have a windows form that needs to be able to check the windows screen saver settings (Is it active, is it under 15 minutes, is "on resume, display logon" active) Essentially if all of those are true the user gets a nice big PASS if not the user gets a big FAIL in a textbox. I have looked online and have found nothing that accomplishes this. I was thinking I would check the settings through windows registry since I will have to do this method of other system settings anyway.

(I used to use a BAT to accomplish this which I will post below for context, but I need somethings compatible with vista and up that displays the results in a user-friendly manner)

echo The following check is for 15 minute inactive lock
echo if true the setting will be set to 1 of false 0
echo            
echo is the screen saver active
reg query "HKCU\Control Panel\Desktop" /v ScreenSaveActive
echo is the screen saver locking the device
reg query "HKCU\Control Panel\Desktop" /v ScreenSaverIsSecure
echo How long until the screen saver activates (900 or below for compliance) 
reg query "HKCU\Control Panel\Desktop" /v ScreenSaveTimeOut
reg query "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\GroupPolicyObjects"

Solution

  • It sounds like you're trying to read a registry key and set a Boolean based on the value. If that's the case, this should help:

    RegistryKey regDesktop = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop");
    
    bool isScreenSaverActive = regDesktop != null && 
        regDesktop.GetValue("ScreenSaveActive").ToString() == "1";
    

    If the settings you described in your question are the only ones you want to check, here's a method that will return true if they exist and match your expected values (ScreenSaveActive == 1, ScreenSaverIsSecure == 1, and ScreenSaveTimeOut <= 900):

    public static bool LockSettingsAreCompliant()
    {
        bool lockSettingsAreCompliant = false;
    
        try
        {
            using (var regKey = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop"))
            {
                lockSettingsAreCompliant =
                    regKey.GetValue("ScreenSaveActive").ToString() == "1" &&
                    regKey.GetValue("ScreenSaverIsSecure").ToString() == "1" &&
                    int.Parse(regKey.GetValue("ScreenSaveTimeOut").ToString()) <= 900;
            }
        }
        catch
        {
            // Swallow exceptions and let the method return false
        }
    
        return lockSettingsAreCompliant;
    }
    

    And then you can use this method like the following to set the textbox text:

    screenSaver.Text = LockSettingsAreCompliant() ? "PASS" : "FAIL";