Disabling a screensaver when running scripts

During the time the scripts are being executed, at the most malapropos moment, the screensaver may kick in or the computer may go into the sleep mode. The simplest way to avoid such mishaps is to completely turn off these working modes manually. In this recipe, we will consider a way to do so programmatically, if switching those modes manually is not acceptable to you by any reason.

How to do it...

To programmatically disable the monitor, we need to perform the following steps:

  1. To disable the screensaver, it is enough to evoke the API-function SystemParametersInfo, passing it the necessary parameters:
    Win32API.SystemParametersInfo(Win32API.SPI_SETSCREENSAVEACTIVE, false, null, 0);
  2. Disabling the sleep mode of your computer and preventing the monitor snooze is a little more complicated and requires calling the SetThreadExecutionState function from the kernel32.dll file within the predefined time intervals. The function itself will appear as follows:
    function disableSleep()
    {
      var ES_SYSTEM_REQUIRED = 0x00000001;
      var ES_DISPLAY_REQUIRED = 0x00000002;
    
      var kernel = DLL.DefineDLL("kernel32");
      var lib = DLL.Load("c:\Windows\System32\kernel32.dll");
      var proc = kernel.DefineProc("SetThreadExecutionState", vt_i2, vt_void);
      lib.SetThreadExecutionState(ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED);
    }
  3. The function call in the script will be made in the following manner:
    Utils.Timers.Add(30000, "Unit1.disableSleep", true);

    Here Unit1 is the name of the unit, in which the disableSleep function has been defined.

How it works...

With the help of the Utils.Timers.Add method, we create a timer that will launch a specific function (in our case, disableSleep from the Unit1 unit) within the set interval (in our case, within 30 seconds).

The disableSleep function itself will include the dynamic kernel32.dll library and call the predefined SetThreadExecutionState function. We pass into this function the only parameter that contains the following two flags:

  • ES_SYSTEM_REQUIRED: This flag requires the system should work in the normal working mode, preventing sleep or snoozing inactivity.
  • ES_DISPLAY_REQUIRED: This flag prevents monitor fading.

Note that disabling the screensaver makes permanent system changes, while preventing the monitor fading works only when scripts run.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.39.60