9

How can I do this in a C# program? I'm pretty sure it should be possible, since various media programs for example do this so the computer doesn't go into stand-by while watching a movie, etc.

So, if I for example create a plain and basic WinForm application, what do I need to do to prevent a laptop from going into Stand-By as long as this application is running?

Svish
  • 152,914
  • 173
  • 462
  • 620

1 Answers1

12

I think you'll have to P/Invoke. But don't be scared... it's pretty easy.

SetThreadExecutionState is your friend. It's available in the PInvoke project, also available on NuGet.

Andrew Arnott
  • 80,040
  • 26
  • 132
  • 171
  • Looks perfect! Can't test it until tonight or tomorrow though, but it looks right :) – Svish Apr 25 '09 at 15:04
  • Do I have to set the state back when my application exits? Or, since it is a per thread/application thing, will it go back to normal automatically? – Svish May 23 '09 at 15:24
  • Unless the documentation states you need to go back manually, I'd say that you probably don't have to set it back if you mean for it to last the life of your app. – Andrew Arnott May 24 '09 at 01:24
  • From the documentation you linked: 'Also note that this setting is per thread/application not global'. – jv42 Jul 07 '14 at 12:12
  • Dan G said in his answer that the proposed solution doesn't work in Windows 10. – nalply Jan 25 '16 at 20:43
  • Hello does this solution prevent computer to sleeping when your application is running? – Shift 'n Tab Aug 20 '16 at 10:01