【问题标题】:Use SetThreadExecutionState with app that doesn't already prevent sleep mode将 SetThreadExecutionState 与尚未阻止睡眠模式的应用程序一起使用
【发布时间】:2015-11-01 19:24:01
【问题描述】:

在 Windows 7 和 10 上,Spotify 应用不会阻止显示屏关闭或系统进入睡眠模式(至少在我使用的 3 台 Windows 机器上)。有没有办法启动应用程序并将 SetThreadExecutionState 函数合并到该线程中以防止显示在应用程序运行时休眠?或者任何其他可以实现该结果的功能?

我目前使用两个单独的 .bat 文件来启动和关闭应用程序,这些文件会更改睡眠计时器,但这非常笨拙,所以我更喜欢合适的应用程序来执行此操作。

【问题讨论】:

  • 在 C 语言中相当简单:调用 SetThreadExecutionState,启动 Spotify,等待 Spotify 退出,然后自己退出。我想同样的方法也适用于 C#。
  • 感谢您的回复。我不喜欢使用任何特定的语言,那在 C 中会是什么样子?

标签: c# windows-7 windows-10 thread-sleep spotify-desktop


【解决方案1】:

此 c# 解决方案不使用 SetThreadExecutionState 函数,但您提到您已经有 .bat 文件来更改睡眠计时器,因此您可以将其中的命令复制到此处。 C# 控制台应用程序:

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");
        }
    }
}

添加更多 Process.Start 行以更改休眠等。

【讨论】:

  • 该解决方案经测试适用于 Win 7 和 10。我将spotify.StartInfo.FileName = "Spotify.exe"; 的完整文件路径替换为spotify.StartInfo.FileName = "C:\\Mypath\\Spotify.exe"; 以使其正常工作。我还将它设置为作为 Windows 应用程序运行,因此控制台不会悬停在后台,根据@Hans Passant 的建议:link。感谢您的帮助!
  • 这种方法的主要问题是,如果程序崩溃或终止,您将无法恢复默认设置。但是,如果您只是在自己的系统上使用它,那可能不是问题。
猜你喜欢
  • 2022-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-02
相关资源
最近更新 更多