24 December 2013

Lock the computer Programmatically using C#

Hi Friends,

Let see how to lock the computer Programmatically using the C# code.  We have to use the function LockWorkStation written inside the user32.dll.  We have to first import the dll in our C# class and we have to declare an extern method LockWorkStation which is already in user32.dll.

Finally We just need to call the method LockWorkStation to lock the system.  We can call this method on button click event or anywhere as per the requirements.

You have to import the user32.dll and declare LockWorkStation method signature as follows.

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

public partial class Form1 : Form
{
    [DllImport("user32.dll", SetLastError = true)]
    private static extern void LockWorkStation();    
        
    public Form1()
    {      
      InitializeComponent();      

      // calling here will lock the computer once the form loaded.      
        bool result = LockWorkStation();

        if( result == false )
        {
           // An error occured
           throw new Win32Exception( Marshal.GetLastWin32Error() );
        }
         
      /*
       * we can call this method on button click or anywhere else
       * as per the requirement.
       */
    }
}

Thanks for reading..!!
Happy Code Sharing..!! :)

No comments:

Post a Comment