Introduction
This is a very simple application that keeps the computer from sleeping. Nothing very fancy, but it seems useful when you cannot control the power options (managed by your domain admin) but you want your PC to stay awake occasionally.
Using the Code
internal static class NativeMethods
{
[DllImport("kernel32.dll")]
public static extern uint SetThreadExecutionState(uint esFlags);
public const uint ES_CONTINUOUS = 0x80000000;
public const uint ES_SYSTEM_REQUIRED = 0x00000001;
}
public partial class MainForm : Form
{
private uint m_previousExecutionState;
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
m_previousExecutionState = NativeMethods.SetThreadExecutionState(
NativeMethods.ES_CONTINUOUS | NativeMethods.ES_SYSTEM_REQUIRED);
if (0 == m_previousExecutionState)
{
MessageBox.Show("Failed to set system state.",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Close();
}
}
protected override void OnClosed(System.EventArgs e)
{
base.OnClosed(e);
if (0 == NativeMethods.SetThreadExecutionState(m_previousExecutionState))
{
}
}
}
Credits