Turn off monitors when locking the computer

  • Gérald Barré

When I lock my computer, it's because I'm going to leave it for a while. I don't want to waste energy by keeping the monitors on and I don't like having a useless source of light. So, I want to turn them off automatically when I lock my computer.

To turn off monitors on Windows, you can use the SendMessage function from the user32.dll library. To avoid creating an executable, I use PowerShell to call this function.

Create a file named turnoff-monitors.ps1 with the following content:

$HWND = -1

$dllImport = @"
    public static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);

$SendMessage = Add-Type -MemberDefinition $dllImport -Name "Win32SendMessage" -Namespace Win32Functions -PassThru

Then, you can create the task using the Task Scheduler. You can use the following PowerShell script to create the task:

# Create the Session Lock trigger
$stateChangeTrigger = Get-CimClass `
    -Namespace ROOT\Microsoft\Windows\TaskScheduler `
    -ClassName MSFT_TaskSessionStateChangeTrigger

$OnLockTrigger = New-CimInstance `
    -CimClass $stateChangeTrigger `
    -Property @{
        StateChange = 7  # TASK_SESSION_STATE_CHANGE_TYPE.TASK_SESSION_LOCK (taskschd.h)
    } `

# Set the action to run the script
$Actions = @(
    New-ScheduledTaskAction `
        -Execute  "C:\Program Files\PowerShell\7\pwsh.exe" `
        -Argument "`"<full path to turnoff-monitors.ps1`"" # TODO: replace with your path

# Set conditions to run the task
$Settings = New-ScheduledTaskSettingsSet -WakeToRun:$false `
                                         -MultipleInstances IgnoreNew `
                                         -RunOnlyIfNetworkAvailable:$false `
                                         -StartWhenAvailable:$false `
                                         -RunOnlyIfIdle:$false `
                                         -AllowStartIfOnBatteries `
                                         -DontStopIfGoingOnBatteries `

# Register the scheduled task
Register-ScheduledTask `
    -TaskName "TurnOff Monitors" `
    -Trigger $OnLockTrigger `
    -Action $Actions `
    -Settings $Settings `
    -TaskPath "\"

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub