⌘BABAKOV.NET Let's code!
100% [dark] [ru]

Programmatically Preventing Device Shutdown and Screen Lock in Win Mobile on C#

Many developers have encountered this issue when their application works perfectly until the device goes into sleep mode. Or when you need to keep the screen on for a long time without touching the screen (e.g., when you're creating your own navigation system). This is what I encountered and needed to prevent the device from shutting down under any circumstances, or when the batteries run out.

static class PowerControl
    {
        private const int POWER_NAME = 0x00000001;
        internal sealed class PowerMethods
        {
            //Для отмены автовыключения...
            [DllImport("coredll.dll")]
            internal extern static void SystemIdleTimerReset();

            //Для отмены выключения подсветки экрана...
            [DllImport("coredll.dll", SetLastError = true)]
            internal extern static int SetDevicePower(
                    string pvDevice,
                    int dwDeviceFlags,
                    DevicePowerState DeviceState
                );


        }

        //Здесь не вижу смысла переводить и так понятно - перечень состояний...
        public enum DevicePowerState : int
        {
            Unspecified = -1,
            D0 = 0, // Full On: full power, full functionality
            D1, // Low Power On: fully functional at low power/performance
            D2, // Standby: partially powered with automatic wake
            D3, // Sleep: partially powered with device initiated wake
            D4, // Off: unpowered
        }
    }



Now, let's talk about how to use this class:


//Это делаем при выходе из программы      
private void menuItem2_Click(object sender, EventArgs e)
        {
            //Задаём обычный режим для подсветки, затем выходим из приложения.
            int POWER_NAME = 0x00000001;
            PowerControl.PowerMethods.SetDevicePower("BKL1:", POWER_NAME, PowerControl.DevicePowerState.Unspecified);
            Application.Exit();
        }

//Это делаем при загрузке приложения
private void Form1_Load(object sender, EventArgs e)
        {
            //Не даем выключить подсветку (по завершении приложения надо перевести в обычный режим)
            int POWER_NAME = 0x00000001;
            PowerControl.PowerMethods.SetDevicePower("BKL1:", POWER_NAME, PowerControl.DevicePowerState.D0);
            
            //Это таймер который вызывает процедуру что сбрасывает автовыключение (обнуляет счётчик поэтому надо повоторять постоянно).
            System.Threading.AutoResetEvent autoEvent     = new System.Threading.AutoResetEvent(true);
            System.Threading.TimerCallback tcb = new System.Threading.TimerCallback(ProcessTimerEvent);
            //Интервалы такие большие поскольку не имеет смысла вызывать процедуру чаще чем это следует делать.
            System.Threading.Timer timer = new System.Threading.Timer(tcb, autoEvent, 18000, 9000);

        }

//Это сама процедура выполняемая по таймеру и сбрасывающая время до отклбючения.
private static void ProcessTimerEvent(object obj)
        {
            //сбрасываем выключение.
            PowerControl.PowerMethods.SystemIdleTimerReset();
        }



That's it.

P.S.
You can download the example with source code here: devicedontshutdown.rar · 23 downloads

Files

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.