views:

498

answers:

2

Is there an easy way to get notified when user presses Power Off button on it's Windows Mobile device? Using C# of course.

Thanks!

+3  A: 

When the power button is pressed, the power manager will send out a notification of a state change. You can request that the PM send you a notification by calling RequestPowerNotifications You have to send in a handle to a point-to-point messgae queue (managed version here) that will get the notification.

For thos who don't want to write all of the glue to make this work, all of this is already pre-done for you in the SDF's PowerManagement class.

Also be forewarned that just becasue you request the notification does not mean that your app will get the notification before the state change occurs. For example on pwer down it's pretty common that an app won't see the notification, and almost certain that even if you do see it you won't have time to execute anything before suspend actually occurs. Typically your handler will run when the device resumes (followed by any handler for the resume state).

The power manager doesn't wait for you, it simply broadcasts a message. You cannot use this to run code before a shutdown.

ctacke
Hmph... I have sound playing that continues to run even if power button is pressed... so I'll try to just set switch to autoplay=false;
kape123
Any idea why I'm getting "Could not load type 'OpenNETCF.WindowsCE.PowerManagement' from assembly 'OpenNETCF.WindowsCE" when I try to use PowerManagement class?
kape123
Sounds like you have an assembly version mismatch or something - maybe multiple copies of different versions of SDF binaries or something.
ctacke
Yeah... it was my genius idea to copy DLL into solution folder, not knowing that it requres three more DLLs: opennetcf.dll, opennetcf.configuration.dll and opennetcf.windowsce.messaging.dll ... it's definitely time to get some sleep. Thanks for your help...
kape123
And you were right, this event is pretty much useless... sometimes I manage to set flag to false, sometimes not... damn race condition
kape123
A: 

Unfortunately, on the Windows CE 6 device i am using, CreateMsgQueue does not exist in CoreDll. Any other suggestions?

The only thing i can think of is continually checking Environment.TickCount against the device's real time clock. If time has moved forward but not the tick count, then presumably the device was sleeping.

Dont like this solution because it will get tricked if the time jumps due to a failure in the device's real time clock

ronzul
Can you change the image? CreateMsgQueue is a really, really common API and I'm surprised your OS doesn't have it. I'm not saying it doesn't, but images stripped down that far really have limited capabilities. I'd try hard to either create a new OS with queue support or talk with the OEM about adding it.
ctacke
I actually gave up on this... it's clear demonstration of how broken WM is ;(
kape123