Solved

Urgent: start and shut down

Posted on 2010-08-16
6
639 Views
Last Modified: 2013-12-21
Hi,

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
0
Comment
Question by:mkk39
  • 3
  • 3
6 Comments
 
LVL 24

Expert Comment

by:alexey_gusev
ID: 33444069
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
0
 

Author Comment

by:mkk39
ID: 33444418
Please guide me more regarding shutting down

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

Expert Comment

by:alexey_gusev
ID: 33444475
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)
    powerNotifier.Stop()

End Sub

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

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()
        t.Start()
    End Sub
 
    Public Sub [Stop]()
        done = True
        t.Abort()
    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")
        Try
            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")
                    Else
                        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

0
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 

Author Comment

by:mkk39
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

0
 

Author Comment

by:mkk39
ID: 33444924
I am checking with Emulator 6.5
0
 
LVL 24

Accepted Solution

by:
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
0

Featured Post

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
moto 4g plus memory usage 30 46
Help with preventing selection from a combobox 11 35
Change to file doesn't show up 16 57
Groupbox Control ? 2 19
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 (https://www.appcelerator.com/). 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.
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

820 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