Search code examples
c#windows-7windows-10thread-sleepspotify-desktop

Use SetThreadExecutionState with app that doesn't already prevent sleep mode


On Windows 7 & 10, the Spotify app doesn't prevent the display from turning off or the system going into Sleep mode (at least on the 3 windows machines I'm using). Is there a way to launch the app and incorporate the SetThreadExecutionState function into that thread to prevent the display sleeping while the app is running? Or any other function that will achieve that outcome?

I currently launch and close the app with two separate .bat files that change the sleep timers, but this is pretty clunky so I'd prefer a proper application to do it.


Solution

  • This c# solution doesn't use SetThreadExecutionState function, but you mentioned you already have .bat files to change the sleep timers, so you can copy the commands from them into here. C# console application:

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                var spotify = new Process();
                spotify.StartInfo.FileName = "Spotify.exe";
                spotify.StartInfo.Arguments = "-v -s -a";
                Process.Start("powercfg", "-CHANGE -monitor-timeout-ac 0");
                spotify.Start();
                spotify.WaitForExit();
                var exitCode = spotify.ExitCode;
                spotify.Close();
                Process.Start("powercfg", "-CHANGE -monitor-timeout-ac 1");
            }
        }
    }
    

    Put more Process.Start lines to alter hibernate, etc.