Lock, Sleep or Hibernate Windows using C#

January 28, 2009 | By

I don’t think there is a Windows developer who has not done this with his or her favorite programming language. So here is the C# version. Putting Windows in Sleep or Hibernate mode can be done with one line of code using the Windows.Forms.Application object’s SetSuspendState method, and locking can be done using Win32’s LockWorkStation function.

SetSuspendState takes three arguments and they are all required. The first is one of the constants of the enum called PowerState, which tells the method to sleep or hibernate. The second argument is a bool and when set to true, Windows is forced into sleep or hibernation. And the third is also a bool which if set to true stops Windows from restoring the system’s power status to active on a wake event. So to put Windows into sleep or hibernate mode, and later restore it without any problem the second and third arguments should be false;

Calling the Win32’s LockWorkStation function in the user32.dll file locks Windows. The function takes no arguments. To be able to call the function import user32.dll using DllImport.


Download Source Code


Filed in: WinForms | Tags: , ,

Comments (7)

  1. ƒяº$Ο„

    damn., it’z all i’am searching for months….
    it’z kool as hell’.,
    thankyu’ buddy….

  2. BassThumpin

    Nice, found exactly what i was looking for. thanks.

  3. cheong hun, kim

    Thanks for sharing yours informations. πŸ™‚

  4. rea

    Thanks a lot!!!!!! πŸ˜€ πŸ˜€ πŸ˜€

  5. Gazal

    Thanks a lot πŸ™‚

  6. Vikram

    Its not working for connected standby. πŸ™
    Do you know how to suspend to CS?