Search code examples
c#visual-studio-2015windows-services

Programmatically Lock workstation from Windows Service


From my Windows Service, I'm trying to lock my Workstation using the below code:

[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool LockWorkStation();

if (!LockWorkStation()){
 //Workstation was unable to lock(Write this on event log)
}

but the above code is not working.

Anybody has a solution for this?


Solution

  • A Windows service does not run on the desktop, so you can't call it from the service.

    From the LockWorkStation documentation, emphasis mine:

    The LockWorkStation function is callable only by processes running on the interactive desktop. In addition, the user must be logged on, and the workstation cannot already be locked.

    It might be a hack, but maybe you could create a tray application that can, in response to some sort of interprocess call from the service, call LockWorkStation.

    If you don't like the visible nature of a tray application, consider creating a console application that spawns a thread to wait for the call, and runs windowless when the user logs in.

    Another possibility is creating a Windows application that never creates a UI window. This is definitely what you want to do if you use the data copy API.

    The key here, is that something has to be running in the user's interactive context.

    For reference, you can look at Microsoft's MSDN topic on IPC.