Urgent: start and shut down

Posted on 2010-08-16
Last Modified: 2013-12-21

It is for windows mobile.

My requirement are:

1) As mobile starts, I need to know its time
2)As mobile turned off, I need to know its time.

How can I get to know when mobile starts and when it shuts down. I need help using C#. Is it possible by anyway?

Thank you
Question by:mkk39
  • 3
  • 3
LVL 24

Expert Comment

ID: 33444069
depending on how accurate you want it to be, you have few options:

- gives you the time from the system start (in ms)

- you might add your app to \Windows\StartUp and get it started and get the current time

- you might add your app to the same area in registry as gwes.exe etc etc, so it'll be started very early and record the time there (HKLM\Init if I remember correctly - you'll see it straight away on Remote Registry Editor)

- for shutting down - you would need Power Management API for that, OpenNETCF guys wrote few samples in C#, there is also PowerManagement Class ( in OpenNETCF - you have seen it probably

Author Comment

ID: 33444418
Please guide me more regarding shutting down

How can I know shut down using power management?
LVL 24

Expert Comment

ID: 33444475
have a look at below snippets, I've used them in one of the projects like this (convert code to c# at

Private WithEvents powerNotifier As New PowerNotifications()

Private Sub xxxForm_Closing(...)
    PowerManagement.PowerPolicyNotify(PowerManagement.PPN_UNATTENDEDMODE, False)

End Sub

Private Sub xxxForm_Load(...)
    PowerManagement.PowerPolicyNotify(PowerManagement.PPN_UNATTENDEDMODE, True)

End Sub
'====================================== PowerManagement utilities

Imports System.Runtime.InteropServices


<CLSCompliant(False)> _

Public Class PowerManagement


    Public Enum DevicePowerState As Integer

        Unspecified = -1

        ' Undefined state

        FullOn  'D0 = 0

        ' Full On: full power, full functionality

        LowOn   'D1

        ' Low Power On: fully functional at low power/performance

        StandBy 'D2

        ' Standby: partially powered with automatic wake

        Sleep   'D3

        ' Sleep: partially powered with device initiated wake

        Off     'D4

        ' Off: unpowered

    End Enum


    Public Const POWER_NAME As Integer = &H1

    Public Const POWER_FORCE As Integer = &H1000

    Public Const PPN_UNATTENDEDMODE As Integer = &H3


    <DllImport("coredll.dll")> _

    Public Shared Function PowerPolicyNotify(ByVal dwMessage As Integer, ByVal dwData As Boolean) As Boolean

    End Function


    <DllImport("CoreDll.DLL", EntryPoint:="SetPowerRequirement", SetLastError:=True)> _

    Public Shared Function SetPowerRequirement(ByVal pvDevice As [String], ByVal DeviceState As Integer, ByVal DeviceFlags As Integer, ByVal pvSystemState As IntPtr, ByVal StateFlags As Integer) As IntPtr

    End Function


    <DllImport("CoreDll.DLL", EntryPoint:="ReleasePowerRequirement", SetLastError:=True)> _

    Public Shared Function ReleasePowerRequirement(ByVal hPowerReq As IntPtr) As UInteger

    End Function


    <DllImport("coredll.dll", EntryPoint:="SystemIdleTimerReset", SetLastError:=True)> _

    Public Shared Sub SystemIdleTimerReset()

    End Sub


End Class

'==================================================== Power Notifications

Imports System.Threading

Imports System.Runtime.InteropServices

Imports Devart.Data.MySql

Imports System.Data.SqlServerCe

Imports System.Data


<CLSCompliant(False)> _

Public Class PowerNotifications

    Private ptr As IntPtr = IntPtr.Zero

    Private t As Thread = Nothing

    Private done As Boolean = False


    <DllImport("coredll.dll")> _

    Private Shared Function RequestPowerNotifications(ByVal hMsgQ As IntPtr, ByVal Flags As UInteger) As IntPtr

    End Function


    <DllImport("coredll.dll")> _

    Private Shared Function WaitForSingleObject(ByVal hHandle As IntPtr, ByVal wait As Integer) As UInteger

    End Function


    <DllImport("coredll.dll")> _

    Private Shared Function CreateMsgQueue(ByVal name As String, ByRef options As MsgQOptions) As IntPtr

    End Function


    <DllImport("coredll.dll")> _

    Private Shared Function ReadMsgQueue(ByVal hMsgQ As IntPtr, ByVal lpBuffer As Byte(), ByVal cbBufSize As UInteger, ByRef lpNumRead As UInteger, ByVal dwTimeout As Integer, ByRef pdwFlags As UInteger) As Boolean

    End Function


    Public Sub New()

        Dim options As New MsgQOptions()

        options.dwFlags = 0

        options.dwMaxMessages = 20

        options.cbMaxMessage = 10000

        options.bReadAccess = True

        options.dwSize = CUInt(System.Runtime.InteropServices.Marshal.SizeOf(options))

        ptr = CreateMsgQueue("someQueueName", options)

        RequestPowerNotifications(ptr, 1)

        t = New Thread(New ThreadStart(AddressOf DoWork))

    End Sub


    Public Sub Start()


    End Sub


    Public Sub [Stop]()

        done = True


    End Sub


    Const PdaOff As Integer = 2

    Const PdaOn As Integer = 1

    Public Shared Event OnPowerStateChangedEvent(ByVal state As Integer)


    Public Const POWER_STATE_ON As UInteger = &H10000             ' on state

    Public Const POWER_STATE_OFF As UInteger = &H20000            ' no power, full off

    Public Const POWER_STATE_CRITICAL As UInteger = &H40000       ' critical off

    Public Const POWER_STATE_BOOT As UInteger = &H80000           ' boot state

    Public Const POWER_STATE_IDLE As UInteger = &H100000          ' idle state

    Public Const POWER_STATE_SUSPEND As UInteger = &H200000       ' suspend state

    Public Const POWER_STATE_UNATTENDED As UInteger = &H400000    ' Unattended state.

    Public Const POWER_STATE_RESET As UInteger = &H800000         ' reset state

    Public Const POWER_STATE_USERIDLE As UInteger = &H1000000     ' user idle state

    Public Const POWER_STATE_BACKLIGHTON As UInteger = &H2000000  ' device screen backlight on

    Public Const POWER_STATE_PASSWORD As UInteger = &H10000000    ' This state is password protected.


    Private Sub DoWork()

        Dim buf As Byte() = New Byte(9999) {}

        Dim nRead As UInteger = 0, flags As UInteger = 0, res As UInteger = 0


        Debug.WriteLine("starting loop")


            While Not done

                res = WaitForSingleObject(ptr, 1000)

                If res = 0 Then

                    ReadMsgQueue(ptr, buf, CUInt(buf.Length), nRead, -1, flags)

                    Dim flag As UInteger = ConvertByteArray(buf, 4)

                    Dim msg As String = Nothing

                    Dim powerState As Integer = 0

                    Utils.LogIt("Flag: " & flag.ToString("X"))

                    If ((flag And POWER_STATE_ON) = POWER_STATE_ON) Or _

                       ((flag And POWER_STATE_IDLE) = POWER_STATE_IDLE) Or _

                       ((flag And POWER_STATE_USERIDLE) = POWER_STATE_USERIDLE) Or _

                       ((flag And POWER_STATE_BACKLIGHTON) = POWER_STATE_BACKLIGHTON) Then

                        powerState = PdaOn

                        Utils.LogIt("Detected powerOn-like state")

                    ElseIf ((flag And POWER_STATE_OFF) = POWER_STATE_OFF) Or _

                           ((flag And POWER_STATE_SUSPEND) = POWER_STATE_SUSPEND) Or _

                           ((flag And POWER_STATE_UNATTENDED) = POWER_STATE_UNATTENDED) Then

                        powerState = PdaOff

                        Utils.LogIt("Detected powerOff-like state")


                        Utils.LogIt("Detected intermediate state")

                    End If

                    If powerState > 0 Then

                        RaiseEvent OnPowerStateChangedEvent(powerState)

                    End If

                End If

            End While

        Catch ex As Exception

            If Not done Then

                Debug.WriteLine("Got exception: " & ex.ToString())

            End If

        End Try

    End Sub


    Private Function ConvertByteArray(ByVal array As Byte(), ByVal offset As Integer) As UInteger

        Dim res As UInteger = 0

        res += array(offset)

        res += array(offset + 1) * CUInt(&H100)

        res += array(offset + 2) * CUInt(&H10000)

        res += array(offset + 3) * CUInt(&H1000000)

        Return res

    End Function


    <CLSCompliant(False)> _

    <StructLayout(LayoutKind.Sequential)> _

    Public Structure MsgQOptions

        Public dwSize As UInteger

        Public dwFlags As UInteger

        Public dwMaxMessages As UInteger

        Public cbMaxMessage As UInteger

        Public bReadAccess As Boolean

    End Structure

End Class

Open in new window

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.


Author Comment

ID: 33444899
It did not work for shut down. Once it captured shut down, dont know why  ratio looked 1:8, i decreased wait time to 500 instead of 1000 in WaitForSingleObject. Still no result


Author Comment

ID: 33444924
I am checking with Emulator 6.5
LVL 24

Accepted Solution

alexey_gusev earned 500 total points
ID: 33444946
well, the emulator is not the ideal target for power management :)
better test it on real device. above code works just fine, detects when the user is trying to turn off the screen only and turn off the device itself

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Contant UI messages in .NET 1 40
DataGridView 2 29
Total in textboxes 9 35
Why, and when, to use Windows Workflow 1 17
Preface: This article is part of a series focused on cross platform mobile app development (specifically Android and iOS) using the Alloy framework and Titanium Studio made by Appcelerator ( This article presumes a wor…
You should read OS supplied guidelines before developing. I can't stress that enough. The guidelines will help you understand the reasons mobile app developers do what they do.  Apple is very particular when they review appstore submissions.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now