Compilenix's Blog - Windows: Lock AND turn off monitor

RSS Feed | Find Stuff

Windows: Lock AND turn off monitor using Windows API, C#, PowerShell and a HotKey.


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 SendMessage(
            IntPtr hWnd,
            UInt32 Msg,
            IntPtr wParam,
            IntPtr lParam
        );
        [DllImport("user32.dll", EntryPoint = "LockWorkStation")]
        private static extern IntPtr LockWorkStation();

        public static void PowerOff() {
            SendMessage(
                (IntPtr)0xffff, // HWND_BROADCAST
                0x0112,         // WM_SYSCOMMAND
                (IntPtr)0xf170, // SC_MONITORPOWER
                (IntPtr)0x0002  // POWER_OFF
            );
        }

        public static void Lock() {
            LockWorkStation();
        }
    }
}
'
[Utilities.Display]::PowerOff()
[Utilities.Display]::Lock()


Stiched together with:
- github.com -> Hexalon/Lock-Computer.ps1
- www.powershellmagazine.com -> #PSTip How to switch off display with PowerShell
- superuser.com -> How can I bind a keyboard shortcut to start a specific application in Windows 7?