How to lock workstation/desktop programmatically in C#?

Here, we have to use the external windows API to perform operations on workstation/desktop . For this it is required to include the following directive first,

using System.Runtime.InteropServices;


Now add the declaration of the API function to a class. If you are using the API function from a single class, you can declare it in the same class. If it is required to be shared across multiple classes, you should create a separate class to contain API methods and change the declaration to make the method public or internal. Here is the API declaration,

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

Now let's check, how to use this function to lock desktop/workstation.

if (!LockWorkStation())
{
    MessageBox.Show("Unable to lock desktop/workstation!");
} 
Here, LockWorkStation method is called and its return value is verified by an conditional if statement
If the result is true, no further action is necessary. Otherwise message box is displayed, indicating that the locking attempt failed.

Comments

Popular posts from this blog

Auto Scroll in Common Controls

Convert typed library (.tlb) to .net assembly?

Disable close button on form - C#