Command-line (cmd) command to lock a windows machine

rundll32.exe user32.dll,LockWorkStation

I've been warned that this isn't recommended (except by Microsoft). The warnings are also centered around the command's close relative, ExitWindowsEx (Which shuts down the computer). I've never had any issues with it, but YMMV.

Schlump: The poodle-monkey may be right. The legend warns that the code is powerful and dangerous.
Nudar: My God. We'd better use it only three or four times. Six, max.
Nibbler: But even a single use could shatter the universe!
Nudar: Got it. Two or three times.

(Source)


If you have access to Visual Studio's C++ compiler here's the (extremely complicated) source:

//
//LockWorkStation.cpp
//
//Locks the console.
//
//To compile (VC++ 2003, on one line):
//
//      cl.exe /W4 LockWorkStation.cpp /link /RELEASE /OPT:REF /OPT:NOWIN98
//                  /ENTRY:mainStartup /SUBSYSTEM:CONSOLE kernel32.lib
//

#if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0500)
    #undef _WIN32_WINNT
    #define _WIN32_WINNT 0x0500 
#endif
#include <windows.h> 

void mainStartup(void)
{
    LockWorkStation(); 
    ExitProcess(0);
}

Note that in Windows Vista/7, you can use the command tsdiscon to disconnect a Remote Desktop session/lock your workstation.

If you use the rundll32.exe user32.dll, LockWorkStation command in a Remote Desktop session (in Windows 7/Vista), the session will continue, but you will just see the lock screen in the Remote Desktop window.