Lock windows workstation using Python

Question:

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.

Asked By: ThiefMaster

||

Answers:

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()
Answered By: ThiefMaster

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)
Answered By: Mahmoud Hossam

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("cmdn")

    sleep(0.500)

    pyautogui.typewrite("rundll32.exe user32.dll, LockWorkStationn")

Answered By: Mounesh
import pyautogui

from time import sleep

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

pyautogui.typewrite("cmdn")

sleep(0.500)

pyautogui.typewrite("rundll32.exe user32.dll, LockWorkStationn")
Answered By: Rocky
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.