특정 프로그램이 실행 중일 때 PC가 잠들지 않도록 하시겠습니까?

특정 프로그램이 실행 중일 때 PC가 잠들지 않도록 하시겠습니까?

저는 휴대폰 미러링 프로그램( scrcpy)을 가지고 있고 노트북이 10분 후에 절전 모드로 전환되도록 설정했습니다. 주로 라이브 TV를 시청하는 데 사용하는데 노트북이 실행되는 동안에는 전원이 꺼집니다. 웹에서 읽어본 후 powercfg -requestsoverride해당 프로그램을 사용해 보았지만 작동하지 않는 것 같습니다. 나는 무엇을 해야 합니까?

편집하다:저는 Windows 10 BTW를 사용하고 있습니다.

답변1

디스플레이 켜기 유지- 프로그램 실행 중 절전 모드 또는 디스플레이 꺼짐을 방지하는 프로그램을 실행합니다.

이는 Windows 10(Windows Vista 이후)에 내장된 컴파일러를 사용합니다. 세 개의 VB.NET 컴파일러와 세 개의 C# 컴파일러가 있습니다. 각 텍스트 파일을 동일한 폴더에 복사하고 배치 파일을 두 번 클릭하여 프로그램을 만듭니다.

이는 API 호출을 사용합니다.SetThreadExecutionState(https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setthreadexecutionstate) 이는 프로그램이 창에 절전 모드를 설정하지 않도록 지시하는 방법입니다.

프로그램 실행 중 절전 모드 또는 디스플레이 꺼짐을 방지하는 프로그램을 실행합니다.

사용

 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

에서https://winsourcecode.blogspot.com/2020/05/keepdisplayon-runs-program-preventing.html

답변2

vbs 스크립트를 컴파일할 필요는 없습니다. 이는 제가 방금 게시한 Powershell 스크립트로 수행할 수 있습니다.GitHub(그리고 아래). 이 스크립트를 사용하면 시스템( ) 또는 시스템과 디스플레이( ) 모두를 절전 모드에서
유지하기 위해 모니터링하려는 프로세스 목록을 전달할 수 있습니다 . 각 목록의 프로세스에 초점이 있거나 일반적으로 최소화/숨겨지지 않은 경우( 매개변수에 따라) 디스플레이 절전 모드를 방지할 수 있습니다. 사용자 정의 가능한 폴링 속도( )를 사용하여 한 번 또는 무한정( ) 실행할 수 있습니다 . 사용 예:-requiresSystem-requiresDisplay-focusOnly-oneTime-pollingRate

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

코드 자체

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

답변3

올가미 처리특정 프로세스가 실행 중일 때 PC가 절전 모드로 전환되지 않도록 하는 기능이 있습니다. 이것은 이것을수면 방지규칙으로, 디스플레이에만 적용할 수도 있고 PC 전체에 적용할 수도 있습니다. 내부적으로는SetThreadExecutionState'Governor' 서비스에서 호출되는 API입니다.

절전 방지(깨어 있음) 규칙을 제공하는 프로세스 올가미 상황에 맞는 메뉴

관련 정보