Urgent: start and shut down


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
Who is Participating?
alexey_gusevConnect With a Mentor Commented:
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
depending on how accurate you want it to be, you have few options:

- http://msdn.microsoft.com/en-us/library/system.environment.tickcount.aspx 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 (http://www.opennetcf.com/library/sdf/html/d3976aad-f969-c1e4-0dc4-dc146d338857.htm) in OpenNETCF - you have seen it probably
mkk39Author Commented:
Please guide me more regarding shutting down

How can I know shut down using power management?
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

have a look at below snippets, I've used them in one of the projects like this (convert vb.net code to c# at developerfusion.com):

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

mkk39Author Commented:
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

mkk39Author Commented:
I am checking with Emulator 6.5
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.