c# - Detect PowerModeChange and wait for execution -


i want run save routines when computer suspends. therefore use onpowerchange-event detect when suspends , resumes. unfortunately me save routine needs 3-5 seconds execute.

when receive suspend event computer shuts down within 1-2 seconds , routine isn't executed completely.

how can prevent suspend until routine finished?

systemevents.powermodechanged += onpowerchange;   private void onpowerchange(object s, powermodechangedeventargs e) {      switch (e.mode)     {         case powermodes.resume:             switchedifier(true);             break;         case powermodes.suspend:             switchedifier(false);             break;     } } 

there unmanaged apis can this, shutdownblockreasoncreate , shutdownblockreasondestroy.

its important note these 2 functions must paired, when call one, have make sure call other 1 (for example, in event of exception), otherwise shutdown may blocked indefinitely.

this cause dialog show telling user programs blocking shutdown, , reason it. important work done , out, because user has option of hitting "force shutdown" button, use.

here example using it:

[dllimport("user32.dll", setlasterror=true)] static extern bool shutdownblockreasoncreate(intptr hwnd, [marshalas(unmanagedtype.lpwstr)] string reason);  [dllimport("user32.dll", setlasterror=true)] static extern bool shutdownblockreasondestroy(intptr hwnd);  //the following needs go in form class, requires valid window handle public void blockshutdownandsave() {     //if calling event, may need invoke on main form     //because calling thread not owner of handle     //will cause "access denied" error.      try     {         shutdownblockreasoncreate(this.handle, "you need patient.");         //do saving here.     }         {         shutdownblockreasondestroy(this.handle);     } } 

short strings reason encouraged user typically won't read long messages. grabs attention, "saving data" or "flushing changes disk". mindful of "do anyway i'm impatient user" button.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -