Turn off monitors when locking the computer
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:
PowerShell
$HWND = -1
$WM_SYSCOMMAND = 0x0112
$SC_MONITORPOWER = 0xF170
$MONITOR_OFF = 2
$dllImport = @"
[DllImport("user32.dll")]
public static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);
"@
$SendMessage = Add-Type -MemberDefinition $dllImport -Name "Win32SendMessage" -Namespace Win32Functions -PassThru
$SendMessage::SendMessage($HWND, $WM_SYSCOMMAND, $SC_MONITORPOWER, $MONITOR_OFF)
Then, you can create the task using the Task Scheduler. You can use the following PowerShell script to create the task:
PowerShell
# 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)
} `
-ClientOnly
# 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 `
-DontStopOnIdleEnd
# 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!
Enjoy this blog?💖 Sponsor on GitHub