17

Is there a way to lock the PC from a Python script on Windows?

I do not want to implement some kind of locking on my own - I'd like to use the same lock screen that's also used when the user presses WIN+L or locks the machine via the start menu.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636

3 Answers3

36

This can be done with the LockWorkStation() function from user32.dll:

This function has the same result as pressing Ctrl+Alt+Del and clicking Lock Workstation.

In Python it can be called using using the ctypes/windll FFI from the Python stdlib:

import ctypes
ctypes.windll.user32.LockWorkStation()
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • @Mandelbrotter How is that comment supposed to be useful? I mentioned in my original question that WIN+L locks the desktop, and my question was obviously about doing it programmatically... – ThiefMaster Feb 13 '21 at 11:16
1

A good solution that makes us avoid using Libraries/DLL files is to use the command prompet/ power shell. try running this command in your cmd rundll32.exe user32.dll, LockWorkStation....The PC is Locked!! so we can use subprocess to run this command like this:

    import subprocess
    cmd='rundll32.exe user32.dll, LockWorkStation'
    subprocess.call(cmd)
  • I think that's pretty messy. also, you shouldn't use `shell=True` here - there's absolutely no need for this here. – ThiefMaster Oct 02 '19 at 12:42
  • I think calling rundll from code that is able to call dll functions directly is messy. Also, `subprocess.call()` should ideally be called with an array (command and args) instead of a string. – ThiefMaster Oct 05 '19 at 17:50
  • i think you are right,but my code above works well with subprocess – Mahmoud Hossam Oct 08 '19 at 12:18
-1

One more solution :

  1. Run command to install the necessary package

    pip install pyautogui

  2. Run the below code

    import pyautogui

    from time import sleep

    pyautogui.hotkey('win', 'r')

    pyautogui.typewrite("cmd\n")

    sleep(0.500)

    pyautogui.typewrite("rundll32.exe user32.dll, LockWorkStation\n")

Mounesh
  • 561
  • 5
  • 18