Verhindern, dass der PC in den Ruhezustand wechselt, wenn ein bestimmtes Programm ausgeführt wird?

Verhindern, dass der PC in den Ruhezustand wechselt, wenn ein bestimmtes Programm ausgeführt wird?

Ich habe ein Programm zur Telefonspiegelung ( scrcpy) und habe meinen Laptop so eingestellt, dass er nach 10 Minuten in den Ruhezustand wechselt. Ich verwende es hauptsächlich, um Live-TV zu schauen, aber der Laptop schaltet sich aus, während es läuft. Nachdem ich im Internet herumgelesen hatte, versuchte ich, powercfg -requestsoverridedieses Programm zu verwenden, aber es scheint nicht zu funktionieren. Was soll ich tun?

BEARBEITEN:Ich verwende übrigens Windows 10.

Antwort1

AnzeigeAnbehalten- Führt ein Programm aus und verhindert, dass während der Programmausführung der Ruhezustand oder das Ausschalten des Displays verhindert wird

Hierbei werden die integrierten Compiler von Windows 10 verwendet (und zwar seit Windows Vista) – es gibt drei VB.NET-Compiler und drei C#-Compiler – kopieren Sie einfach jede Textdatei in denselben Ordner und doppelklicken Sie auf die Batchdatei, um das Programm zu erstellen.

Dies verwendet den API-AufrufThreadExecutionState festlegen(https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setthreadexecutionstate), mit der Programme Windows anweisen, nicht in den Ruhezustand zu wechseln.

Führt ein Programm aus und verhindert, dass der Ruhezustand oder das Ausschalten des Displays während der Programmausführung aktiviert wird.

Benutzen

 KeepDisplayOn "C:\windows\notepad"
 KeepSystemOn "C:\windows\notepad"

@Echo Off
ECHO Three files follow
ECHO PreventSleep.bat
ECHO.
ECHO This file compiles KeepDisplayOn.vb and KeepSystemOn.vb to KeepDisplayOn.exe and KeepSystemOn.exe using the system VB.NET compiler.
ECHO.
ECHO Runs a program preventing sleeping or the display turning off while the program runs
ECHO.
ECHO To Use
ECHO      KeepDisplayOn "C:\windows\notepad"
ECHO      KeepSystemOn "C:\windows\notepad"
ECHO.
C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc "%~dp0\KeepDisplayOn.vb" /out:"%~dp0\KeepDisplayOn.exe" /target:winexe
C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc "%~dp0\KeepSystemOn.vb" /out:"%~dp0\KeepSystemOn.exe" /target:winexe
pause

'KeepSystemOn.vb
imports System.Runtime.InteropServices
Public Module MyApplication 
Public Declare UNICODE Function SetThreadExecutionState Lib "Kernel32" (ByVal esFlags as Integer) as Integer
Public Const  ES_AWAYMODE_REQUIRED = &h40
Public Const  ES_CONTINUOUS = &h80000000
Public Const  ES_DISPLAY_REQUIRED = &h2
Public Const  ES_SYSTEM_REQUIRED = &h1
Public Const  ES_USER_PRESENT = &h4

 Public Sub Main ()
  Dim wshshell as Object
  Dim Ret as Integer
  WshShell = CreateObject("WScript.Shell")
  Ret = SetThreadExecutionState(ES_Continuous + ES_System_Required + ES_Awaymode_Required)
  WshShell.Run(Command(), , True)
 End Sub
End Module

'KeepDisplayOn.vb
imports System.Runtime.InteropServices
Public Module MyApplication 
Public Declare UNICODE Function SetThreadExecutionState Lib "Kernel32" (ByVal esFlags as Integer) as Integer
Public Const  ES_AWAYMODE_REQUIRED = &h40
Public Const  ES_CONTINUOUS = &h80000000
Public Const  ES_DISPLAY_REQUIRED = &h2
Public Const  ES_SYSTEM_REQUIRED = &h1
Public Const  ES_USER_PRESENT = &h4

 Public Sub Main ()
  Dim wshshell as Object
  Dim Ret as Integer
  WshShell = CreateObject("WScript.Shell")
  Ret = SetThreadExecutionState(ES_Continuous + ES_Display_Required + ES_Awaymode_Required)
  WshShell.Run(Command(), , True)
 End Sub
End Module

Aushttps://winsourcecode.blogspot.com/2020/05/keepdisplayon-runs-program-preventing.html

Antwort2

Es ist nicht notwendig, VBS-Skripte zu kompilieren, dies kann durch ein Powershell-Skript erledigt werden, das ich gerade veröffentlicht habe aufGitHub(und weiter unten).
Mit diesem Skript können Sie Listen von Prozessen übergeben, die Sie überwachen möchten, um entweder Ihr System ( -requiresSystem) oder sowohl das System als auch den Bildschirm ( -requiresDisplay) vom Ruhezustand abzuhalten. Der Ruhezustand des Bildschirms kann verhindert werden, wenn ein Prozess aus der jeweiligen Liste im Fokus steht oder generell nicht minimiert/versteckt ist (abhängig vom Parameter). Es kann einmal oder unbegrenzt ( ) mit einer anpassbaren Abfragerate ( ) -focusOnlyausgeführt werden . Anwendungsbeispiel:-oneTime-pollingRate

SnoozeGuard.ps1 -requiresDisplay "mstsc" -requiresSystem "handbrake" -focusOnly 0 -pollingRate 120 -oneTime 0

Code selbst

param (
    [string[]]$requiresSystem,
    [string[]]$requiresDisplay,
    [int]$pollingRate = 120,
    [bool]$focusOnly = $true,
    [bool]$oneTime = $false
)

# Check if PowerState type is already defined (GPT suggests this, not sure why, since for me it does need to do this: possible for compatibility reasons?)
if (-not ([System.Management.Automation.PSTypeName]'PowerState').Type) {
    # Define the PowerState enumeration
    Add-Type @"
        using System;

        [Flags]
        public enum PowerState : uint
        {
            ES_CONTINUOUS = 0x80000000,
            ES_SYSTEM_REQUIRED = 0x00000001,
            ES_DISPLAY_REQUIRED = 0x00000002
        }
"@
}

# Check if NativeMethods type is already defined
if (-not ([System.Management.Automation.PSTypeName]'NativeMethods').Type) {
    # Define the NativeMethods class
    Add-Type @"
        using System;
        using System.Runtime.InteropServices;

        public class NativeMethods
        {
            [DllImport("kernel32.dll", SetLastError = true)]
            public static extern uint SetThreadExecutionState(uint esFlags);

            [DllImport("user32.dll")]
            public static extern IntPtr GetForegroundWindow();

            [DllImport("user32.dll", SetLastError = true)]
            public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
        }
"@
}

if (-not ([System.Management.Automation.PSTypeName]'WindowMethods').Type) {
    # DEfine WindowMethods class
    Add-Type @"
        using System;
        using System.Runtime.InteropServices;
        public class WindowMethods {
            [DllImport("user32.dll")]
            [return: MarshalAs(UnmanagedType.Bool)]
            public static extern bool IsIconic(IntPtr hWnd);
            [DllImport("user32.dll")]
            [return: MarshalAs(UnmanagedType.Bool)]
            public static extern bool IsWindowVisible(IntPtr hWnd);
        }
"@
}

function SetExecutionState {
    param (
        [PowerState]$esFlags
    )

    $state = [PowerState]::ES_CONTINUOUS -bor $esFlags
    
    # Suppress the output of SetThreadExecutionState
    $result = [NativeMethods]::SetThreadExecutionState($state)

    if ($result -eq 0) {
        Write-Host "Error: Unable to set execution state." -ForegroundColor Red
    }

    Get-StateNames -Value ([NativeMethods]::SetThreadExecutionState(0))  # Get the current state
}

function Get-StateNames {
    param (
        [uint32]$Value
    )

    if ($Value -band [PowerState]::ES_SYSTEM_REQUIRED -and $Value -band [PowerState]::ES_DISPLAY_REQUIRED) {
        Write-Host "Fully awake" -ForegroundColor DarkGreen
    }
    elseif ($Value -band [PowerState]::ES_SYSTEM_REQUIRED) {
    Write-Host "System is awake" -ForegroundColor DarkYellow
    }
    elseif ($Value -band [PowerState]::ES_DISPLAY_REQUIRED) {
    Write-Host "Display is awake" -ForegroundColor DarkBlue
    }
    else {
        Write-Host "Feeling sleepy" -ForegroundColor Gray
    }
}

function IsProcessRunning {
    param (
        [string[]]$processName
    )

    foreach ($name in $processName) {
        Write-Host "Searching for ""$name""..." -ForegroundColor Gray
        $process = Get-Process -Name $name -ErrorAction SilentlyContinue
        if ($process) {
            Write-Host "Process ""$name"" found" -ForegroundColor Gray
            return $true
        }
    }

    return $false
}

function IsProcessFocused {
    param (
        [string]$name
    )

    $foregroundWindow = [NativeMethods]::GetForegroundWindow()

    if ($foregroundWindow -eq [IntPtr]::Zero) {
        return $false
    }

    $processId = 0
    [NativeMethods]::GetWindowThreadProcessId($foregroundWindow, [ref]$processId) | Out-Null

    $focusedProcess = Get-Process -Id $processId -ErrorAction SilentlyContinue

    if ($focusedProcess -and $focusedProcess.ProcessName -eq $name) {
        return $true
    }

    return $false
}

function IsProcessVisible {
    param (
        [string]$processName
    )

    # Get the process by name
    $process = Get-Process -Name $processName -ErrorAction SilentlyContinue

    # Check if the process is found
    if ($process -ne $null) {
        # Check if the main window is minimized or hidden
        if ($process.MainWindowHandle -ne [IntPtr]::Zero) {
            $mainWindow = $process.MainWindowHandle
            $isMinimized = [WindowMethods]::IsIconic($mainWindow)
            $isVisible = [WindowMethods]::IsWindowVisible($mainWindow)

            if ($isMinimized -or -not $isVisible) {
                return $false
            } else {
               return $true
            }
        }
    }
    return $false
}

while (($requiresSystem -ne $null -and $requiresSystem.Length -gt 0) -or ($requiresDisplay -ne $null -and $requiresDisplay.Length -gt 0)) {
    if (IsProcessRunning $requiresDisplay) {
        $executionState = [PowerState]::ES_SYSTEM_REQUIRED

        foreach ($name in $requiresDisplay) {
            if (($focusOnly -and (IsProcessFocused $name)) -or (-not $focusOnly -and ((IsProcessFocused $name) -or (IsProcessVisible $name)))) {

                Write-Host "Process ""$name"" wants display" -ForegroundColor Gray
                $executionState = $executionState -bor [PowerState]::ES_DISPLAY_REQUIRED
                break  # Exit the loop once one focused process is found
            }
        }

        SetExecutionState -esFlags $executionState
    } elseif (IsProcessRunning $requiresSystem) {
        SetExecutionState -esFlags ES_SYSTEM_REQUIRED
    } else {
        Write-Host "No processes found" -ForegroundColor Gray
    }

    if ($oneTime) {
        break
    } else {
        Start-Sleep -Seconds $pollingRate
    }
}

# Release the execution state when the process is not running
SetExecutionState -esFlags ES_CONTINUOUS | Out-Null

Antwort3

Prozess-Lassoverfügt über eine Funktion, die den PC davon abhält, zu schlafen, wenn bestimmte Prozesse ausgeführt werden. Dies nennt manSchlaf verhindernRegel, und sie kann nur auf das Display oder den gesamten PC angewendet werden. Intern verwendet sie dieThreadExecutionState festlegenAPI, aufgerufen durch den „Governor“-Dienst.

Kontextmenü von Process Lasso mit der Regel „Schlaf verhindern (Wach halten)“

verwandte Informationen