¿Evitar que la PC se duerma cuando se ejecuta un determinado programa?

¿Evitar que la PC se duerma cuando se ejecuta un determinado programa?

Tengo un programa de duplicación de teléfono ( scrcpy) y configuro mi computadora portátil para que se duerma después de 10 minutos. Lo uso principalmente para ver televisión en vivo, pero la computadora portátil se apaga mientras está funcionando. Después de leer en la web, intenté usarlo powercfg -requestsoverridepara ese programa, pero no parece funcionar. ¿Que se supone que haga?

EDITAR:Estoy usando Windows 10 por cierto.

Respuesta1

Mantener pantalla encendida- Ejecuta un programa que impide dormir o que la pantalla se apague mientras se ejecuta el programa.

Esto utiliza los compiladores incorporados en Windows 10 (y lo han sido desde Windows Vista); hay tres compiladores de VB.NET y tres compiladores de C#; simplemente copie cada archivo de texto en la misma carpeta y haga doble clic en el archivo por lotes para crear el programa.

Esto utiliza una llamada APIEstablecer estado de ejecución de hilo(https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setthreadexecutionstate) que es cómo los programas le dicen a Windows que no duerma.

Ejecuta un programa que impide dormir o que la pantalla se apague mientras se ejecuta el programa.

Usar

 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

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

Respuesta2

No es necesario compilar scripts vbs; esto se puede hacer mediante un script de Powershell, que acabo de publicar enGitHub(y por debajo).
Este script le permite pasar listas de procesos que desea monitorear para evitar que su sistema ( -requiresSystem) o tanto el sistema como la pantalla ( -requiresDisplay) entren en suspensión. Se puede evitar la suspensión de la pantalla si un proceso de la lista respectiva está enfocado o generalmente no está minimizado/oculto (depende del -focusOnlyparámetro). Se puede ejecutar una vez o indefinidamente ( -oneTime) con una tasa de sondeo personalizable ( -pollingRate).
Ejemplo de uso:

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

Código en sí

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

Respuesta3

Proceso de lazotiene una función para evitar que la PC entre en suspensión cuando se ejecutan procesos específicos. A esto lo llama unPrevenir el sueñoregla, y se puede aplicar solo a la pantalla o a toda la PC. Internamente utiliza elEstablecer estado de ejecución de hiloAPI, llamada por su servicio 'Gobernador'.

Menú contextual de Process Lasso que ofrece la regla Prevenir sueño (Mantener despierto)

información relacionada