Skip to content

Instantly share code, notes, and snippets.

@PCHSwS
Forked from oledid/turn-off-screen.ps1
Created April 18, 2021 16:45
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save PCHSwS/39e213aac7c574b89673da8dc575e7fa to your computer and use it in GitHub Desktop.
Save PCHSwS/39e213aac7c574b89673da8dc575e7fa to your computer and use it in GitHub Desktop.
PowerShell: Turn off computer screen
# Source: http://www.powershellmagazine.com/2013/07/18/pstip-how-to-switch-off-display-with-powershell/
# Turn display off by calling WindowsAPI.
# PostMessage(HWND_BROADCAST,WM_SYSCOMMAND, SC_MONITORPOWER, POWER_OFF)
# HWND_BROADCAST 0xffff
# WM_SYSCOMMAND 0x0112
# SC_MONITORPOWER 0xf170
# POWER_OFF 0x0002
Add-Type -TypeDefinition '
using System;
using System.Runtime.InteropServices;
namespace Utilities {
public static class Display
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr PostMessage(
IntPtr hWnd,
UInt32 Msg,
IntPtr wParam,
IntPtr lParam
);
public static void PowerOff ()
{
PostMessage(
(IntPtr)0xffff, // HWND_BROADCAST
0x0112, // WM_SYSCOMMAND
(IntPtr)0xf170, // SC_MONITORPOWER
(IntPtr)0x0002 // POWER_OFF
);
}
}
}
'
[Utilities.Display]::PowerOff()
@PCHSwS
Copy link
Author

PCHSwS commented Apr 18, 2021

Changed SendMessage to PostMessage to not have the script hang upon execution.

@silverjohnes
Copy link

silverjohnes commented Nov 22, 2022

You can also use this command line command based on code above:

powershell.exe (Add-Type '[DllImport("user32.dll")]^public static extern int PostMessage(int hWnd, int hMsg, int wParam, int lParam);' -Name a -Pas)::PostMessage(0xffff,0x0112,0xF170,0x0002)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment