C# Lock, Sleep, and Hibernate Windows

This could be a very uncommon occurrence but you might find a need in C# to set the computers sleep or hibernate state. You might even need to lock the entire pc. .NET has two of the needs built in, the third you will need to do some pinvoking.



// set the computer to hibernate
bool retVal = Application.SetSuspendState( PowerState.Hibernate, false, false );

if( retVal == false )
{
   MessageBox.Show( "Unable to hibernate the system." );
}


// set the computer to suspended
bool retVal = Application.SetSuspendState( PowerState.Suspend, false, false );

if( retVal == false )
{
   MessageBox.Show( "Unable to suspend the system." );
}

// lock the workstation
// we need to import from user32.dll, the LockWorkStation function
[DllImport("user32.dll", SetLastError = true)]  
static extern bool LockWorkStation();  

bool result = LockWorkStation();  
  
if (result == false)  
{  
   // TODO: an error occured
}  


The Application.SetSuspendState is the big call here. Here is the MSDN link:

http://msdn.microsoft.com/en-us/library/system.windows.forms.application.setsuspendstate.aspx

Comments

Popular posts from this blog

String.Replace vs Regex.Replace

C# Form Application in Kiosk Mode/Fullscreen

Javascript numeric only text box