Power Management Article Published

I’ve taken the discussion of the power button and have expanded upon it in the form of an article on power management in Widnows Mobile devices.  I’ve published it at my favorite online dev community site, codeproject.com.  Go over to http://www.codeproject.com/script/Articles/Article.aspx?aid=28886 and take a look at the article.  If you find the information useful then please log in and rate it!

 

My CE Devices

I had to pull out one of my older Pocket PCs for testing something and while I was at it I decided to round up my Windows CE devices and take a picture of them together.  I seem to have quite a bit.  Missing from the history of devices that I’ve owned are an i-mate Jam and the ViewSonic V37.  Regretably I sold one and gave the other to some one that wanted a PocketPC.  I hope to get a Windows Mobile 6 standard device and a Windows CE development kit in the coming months.

 

My Windows CD Devices

 

What Does the Power Button Do?

The iIimpact of unobservable events has long been a subject over which humans have pondered.    Some questions are either well known or commonly shared.

  • If a tree falls in the forest and no one hears it then does it make a sound?
  • When I close the door on the fridge does the light go out?
  • Is Schrodinger’s cat dead or alive?
  • When I press the power button on my Windows Mobile phone do the programs stop running?

These are all questions will all be answered by the end of this blog post. Thanks to the availability of inexpensive electronics such as digital video and audio recorders we can show that falling tress make noises and that the lights in the fridge do go out.  Figuring out what happens when the power button is pressed on Windows Mobile was a little more difficult.

My first attempt at answering this question was based on programs that changed what they were displaying  over their execute cycles.  If the Windows Mobile device suspends when I press the power button then after pressing the button, waiting a few seconds, and pressing it again the program’s display should show the same thing that it did before I pressed the button.  If the device continues to run when I press the power button then after the test I should see something that is noticably different. I ran my test and concluded that the processor continued to run after the power button was pressed.  As it turned out my initial conclusion was wrong.

After performing much more research on the matter I found that my conclusion contradicticted other material I found such as the “Power to the Programmers” post on the Windows Mobile Team Blog. I performed my tests again and increased the amount of time that I left the device in its alleged suspended state.  After successive test I achieved enlightenment.   Pressing the power button on a Windows Mobile Professional device powers down the display and some other hardware, but the processor continues to run.  After a certain amount of time has passed unless a program has indicated a desire to do otherwise the device’s processor will halt until something wakes it up.  When the device is in this state it’s not off; the programs are still in memory.  Windows Mobile Standard devices are always on, there’s no questioning that.

In a forthcoming post I’ll cover the details of power control on Windows Mobile devices.

So the only question that leaves open is whether or not Schrodinger’s cat is alive. I will leave that question unanswerd and hope for the best for his cat.

What Does the Power Button Dp

The impact of unobservable events has long been a subject over which humans have pondered.    Some questions are either well known or commonly shared.

  • If a tree falls in the forest and no one hears it then does it make a sound?
  • When I close the door on the fridge does the light go out?
  • Is Schrodinger’s cat dead or alive?
  • When I press the power button on my Windows Mobile phone do the programs stop running?

These are all questions will all be answered by the end of this blog post. Thanks to the availability of inexpensive electronics such as digital video and audio recorders we can show that falling tress make noises and that the lights in the fridge do go out.  Figuring out what happens when the power button is pressed on Windows Mobile was a little more difficult.

My first attempt at answering this question was based on programs that changed what they were displaying  over their execute cycles.  If the Windows Mobile device suspends when I press the power button then after pressing the button, waiting a few seconds, and pressing it again the program’s display should show the same thing that it did before I pressed the button.  If the device continues to run when I press the power button then after the test I should see something that is noticeably different. I ran my test and concluded that the processor continued to run after the power button was pressed.  As it turned out my initial conclusion was wrong.

After performing much more research on the matter I found that my conclusion contradicted other material I found such as the “Power to the Programmers” post on the Windows Mobile Team Blog. I performed my tests again and increased the amount of time that I left the device in its alleged suspended state.  After successive test I achieved enlightenment.   Pressing the power button on a Windows Mobile Professional device powers down the display and some other hardware, but the processor continues to run.  After a certain amount of time has passed unless a program has indicated a desire to do otherwise the device’s processor will halt until something wakes it up.  When the device is in this state it’s not off; the programs are still in memory.  Windows Mobile Standard devices are always on, there’s no questioning that.

In a forthcoming post I’ll cover the details of power control on Windows Mobile devices.

So the only question that leaves open is whether or not Schrodinger’s cat is alive. I will leave that question unanswered and hope for the best for his cat.

 

MFC and Windows Mobile

One of the things that I love about Microsoft is that once you learn a Microsoft technology parts of it are transferable to other Microsoft Platforms. The .Net technologies are an excellent example of this. There’s also DirectX (portions of which can be used on Windows Mobile devices) and MFC.

Another such technology is MFC (Microsoft Foundation Classes).  MFC is a library of C++ application framework library for creating Windows applications.  It is a native code library, so you have full access to the native API without the need of platform invoke declarations or re-declaring structures for making native calls.  But it also provides several high level classes for creating UI elements and responding to windows messages. I would say that MFC lives half way between .Net based programs and traditional native non-MFC applications.

I am engaging in a project for which it will be easier to use native code.  The project is going to rely on some third party native code libraries with a massive amount structures.  For the first phase of this project I plan to use MFC so that I can make a prototype with the third party library.  Later on I will make an abstraction layer that gives simpler access to the functionality that I need and then I will create a .Net wrapper for it.  In the coming weeks once the project reaches a certain level of functionality, stability, and presentability I’ll be posting the code on CodeProject.com.  I don’t want to say anything about the nature of the project just yet, but I’m sure it will be very popular!

 

Windows Mobile 6.1 Upgrade for the Tilt?

HTC’s support site is in a state of flux for the AT&T Tilt (a version of the HTC TyTn II).  The page is fluctuating between having a description for the Windows Mobile 6.0 ROM and the Windows Mobile 6.1 ROM.  Regardless of which page is displayed the Windows Mobile 6.0 rom is always the target of the download link.  I sent a question to their support department about this and they say the firmware update will be available by the end of the month.  Happy Days are Coming.

 

Teaching the Teachers

If I were to describe my goal with this site it would be summed in one word, “teach.”  I created this site for the purpose of communicating to other developers that have interest in Windows Mobile. My actions thus far have been centered around writing articles for developers. But some times developers are also teachers. I think that others could better take advantage of the information I post here if I make my target audience the developer-teacher.  This means that in addition to the articles I will be including Power Point slides with notes so that a developer-teacher will have information in a presentable form with minimal effort; all they would need to do is add their name to the first slide and optionally apply a theme to the power point slide deck.  I won’t be able to do this for every article because of time constraints (priority is given to my day job) but articles that contain slide will be marked with the “Presentation” tag.

 

Looking for Visible Devices

In a post a few days ago (Your Device is Showing) I mentioned the concerns that a few users had about their devices being visible to other people on their respective phone networks through Resco Explorer. Using a network packet monitoring tool I was able to write some code that performed netbios queries and was able to obtain the same names that Resco Explorer had received.  Requesting the name of a device is straight forward.  Just send a request to the device to be queried into UDP port 137 and extract the name from the response.  The byte stream to send is as follows.

NameRequest = new byte[]{
0x80, 0x94, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x20, 0x43, 0x4b, 0x41,
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
0x41, 0x41, 0x41, 0x41, 0x41, 0x00, 0x00, 0x21,
0x00, 0x01 };

In the response byte stream you can extract the name from the 57th byte of the response to the 75th byte.  The name will be padded with spaces if it is less than 16 characters.  I did run into a problem in implementing this.  Many Windows CE builds don’t contain an implementation for timeout functionality on ports when listening and there doesn’t seem to be way to abort listening for a response without introducing a resource leak.  This is something worth revisiting once I have more information.

 

Auto-launching an Application on Windows Mobile

I submitted an article to codeproject.com a little over a month ago about automatically starting an application base on an event or a schedule. I posted the content of the article here.  To get the source code visit http://www.codeproject.com/script/Articles/Article.aspx?aid=27917

Introduction

Figuring out how to make an application automatically start up had long been a mystery to me. The information was scattered and a bit of research was needed to collect all of. During my research I placed all of my notes in a various documents and have decided to organize them into a single document and share with all. The information presented here was tested on Windows Mobile 5 and Windows Mobile 6 devices but can also be applied to several versions of Windows CE (The OS from which Windows Mobile is derived).

It’s possible to achieve similar functionality by making your own executable that watches system changes through the SystemState class and responding accordingly, but that would cause your program to have a larger footprint.

About the Code

The first methods of automatically starting a program are centered in what I will call configuration tasks; making shortcuts, registry entries, or placing files in specific locations. For these methods I do not provide code examples. Later within this article I discuss methods of automatically launching applications that are setup through code. For these methods I include example code within the article and full source attached to the article.

The code examples rely on some Win32 functions that are called through P/Invoke. Both code examples refer to a project named Win32 which contains the references to these functions. Additionally Win32 also contain a structure and an enumeration needed to properly pass information to the WinAPI functions. To run the code examples you will need a Windows Mobile device (or emulator) and Visual Studio 2008.

Remember that on Windows Mobile devices you should prevent more than one instance of your program from existing in memory (if a second instance is started it should notify the first instance and then immediatly terminate).

What is meant be “auto-start?”

When I use the phrase auto-start I use it to refer to the launching of any program based on an event (other than the user clicking on the program’s icon). A program can be automatically started in one of four ways.

  • A program on a memory card runs as soon as the card is inserted
  • A program is scheduled to start at a predetermined time
  • A program is launched in response to a system change
  • A program launches at device power up

AutoRun from a Memory Card

The user inserting a memory card can cause an application to launch in one of two ways. The memory card could have a program on it that launches upon insertion of the Windows Mobile device could start a program that is already present in its main storage in response to the memory card being inserted. The later would be implemented by registering an application to start on a system change (discussed later).

When a memory card is inserted into a Windows Mobile / Windows CE device the OS automatically looks in a certain folder for a program named Autorun.exe. If that program is found then it is immediately run. The folder in which the OS looks is going to depend on what type of processor that the device has. For an overwhelming majority of Windows Mobile devices that folder will be “/2577”. Here is a table of the possible folder names for other Windows CE devices.

ProcessorFolder Name
ARM 7201824
Arm 8202080
ARM 9202336
ARM 7TDMI70001
Hitachi SH310003
Hitachi SH3E10004
Hitachi SH410005
Motorola 821821
SH3103
SH4104
Strongarm2577

f you already have an application on a memory card that you wanted to autorun.exe but you did not want to rename the executable or place it in this folder then you can always make a second executable whose purpose is to launch your first executable.

Startup Shortcut

A shortcut can be made to an application that you wish to startup automatically and placed in \Windows\StartUp. Use this method if you have a single executable that needs to be started that has no dependencies on other executables. The format of shortcuts on windows mobile devices is simple. It will always be in the form of 00#”<\program Files\path>” where 00 is replaced with the number of characters that appear after the ‘#’ sign, the ‘#’ is a delimiter, and then the complete path to the executable. The following is an example of a shortcut to Windows Media Player.

23#“\windows\wmplayer.exe”

You don’t have to manually create the shortcut though. There is a native API call SHCreateShortcut that will create a shortcut for you. The first argument is the full path to the shortcut to be created and the second arguement is the full path to the file to which the shortcut points.

Starting an Application at Bootup

For Windows Mobile devices the location for autostart entries is HKEY_LOCAL_MACHINE\Init. Unlike the startup entries on a desktop machine (which only require the path to the executable to start) the entries for Windows Mobile devices are a little more structured. There are two keys associated with an application that needs to start up automatically, a LaunchXX key and an optional DependXX key. The XX would be replaced with a number. This number is also called the sequence number The value of LaunchXX is a string value (REG_SZ) that contains the path to the executable to be started. The DependXX key is used to specify on what applications that the current application has dependencies (and thus in what order the applications must be launched). The DependXX key contains a list of word (2 bytes) values that contain the sequence number values of the required applications.

The following screenshot is of the registry on my Windows Mobile 5 phone. Launch21 refers to an application named “coldinit.” If we look at Depend21 we see that “coldinit.exe” has a dependency on an application identified by 0x14 (20 decimal). So “coldinit.exe” must be launched after the app identified in Launch20, “Device.exe.”

Screen shot of Windows Mobile Registry

Applications launched using this method must notify the application of successful startup by calling the SignalStarted(DWORD) function. This function is a native call. For C programs the header to this function is defined in Winbase.h and in the library Coredll.lib. Developers using managed code will need to P/Invoke this method. The functions only argument is the sequence number of the executable. The sequence number is passed to the application as its only command argument. Note that the sequence number is the only argument that the application will be able to receive through the command line arguments. Any other information that must be passed to the application should be passed through configuration files or registry keys.

Starting a Program at a Specified Time

The Windows CE / Windows Mobile OS contains functionality for automatically starting a program at a specified time. The functionality is available through a call to CeRunApAtTime from the CoreDLL library. As mentioned by Jim Wilson in many of his “How Do I” video post on MSDN, this function expects the start time to be specified in the WinAPI SystemTime structure instead of the DateTime structure (CeRunAppAtTime is an unmanaged function called using the platform invoke functionality). Converting a time from a DateTime to a SystemTime is not difficult; there are already WinAPI functions that do this for you. To make calling this function easier I have placed the following code in my Win32Helper class. I’ve also provided an overloaded function to allow the time to be passed as an offset from the current time with a TimeSpan object.

public static void RunAppAtTime(string applicationEvent, DateTime startTime) {     long fileTimeUTC = startTime.ToFileTime();     long fileTimeLocal = 0 ;     SystemTime systemStartTime = new SystemTime();     CoreDLL.FileTimeToLocalFileTime(ref fileTimeUTC, ref fileTimeLocal);     CoreDLL.FileTimeToSystemTime(ref fileTimeLocal, systemStartTime);     CoreDLL.CeRunAppAtTime(applicationEvent, systemStartTime); } public static void RunAppAtTime(      string applicationEvent,       TimeSpan timeDisplacement ) {     DateTime targetTime = DateTime.Now + timeDisplacement;     RunAppAtTime(applicationEvent, targetTime); }  

Where applicationEvent is the full path to the application to start and startTime is the time at which the application should be executed. There’s also an overloaded version of the method that accepts a TimeSpan object instead of a DateTime if you wanted to specify the start time relative to the current time.

If an application were attempting to schedule itself to be restarted at a later time it will need to be able to pass it’s complete path. I used reflection to find that path.

Module[] m = this.GetType().Assembly.GetModules(); target = m[0].FullyQualifiedName;
Screenshot of timed start program

Running the Program because of a System Change

There are a number of system changes that can be used to trigger the execution of a program. The WinAPI function CeRunAppAtEvent is used to associate a program with an event. Once associated that program will be launched every single time that the event occurs! So you must also remember to disassociate the program with the event when you no longer want it to automatically start.

I have created the enumeration in the Win32 class named WhichEvent that contains the ID numbers for the events that can be used to trigger program execution.

When a program is started because of a change in system state a single argument is passed to the program to indicate the state change that triggered the programs execution. (I don’t discuss the details of how to do that here). For a complete list of the possible arguments see the example cod in AutoStartArgumentString.cs.

Enumeration ElementDescription
NOTIFICATION_EVENT_NONEUsed to clear all events associated with a program
NOTIFICATION_EVENT_TIME_CHANGE
NOTIFICATION_EVENT_SYNC_ENDActiveSync synchronization has completed on the device
NOTIFICATION_EVENT_ON_AC_POWERThe unit’s charger is connected
NOTIFICATION_EVENT_OFF_AC_POWERThe unit’s charger is disconnected
NOTIFICATION_EVENT_NET_CONNECTThe device is connected to a network
NOTIFICATION_EVENT_NET_DISCONNECTThe device is disconnected from a network
NOTIFICATION_EVENT_DEVICE_CHANGEA memory card or other device was inserted or removed
NOTIFICATION_EVENT_IR_DISCOVEREDThe device has detected another infrared device
NOTIFICATION_EVENT_RS232_DETECTEDThe device has been connected to an RS232 device
NOTIFICATION_EVENT_RESTORE_ENDA full restore of the device has completed
NOTIFICATION_EVENT_WAKEUPThe device has come out of a suspended state
NOTIFICATION_EVENT_TZ_CHANGEThe time zone of the device has changed
NOTIFICATION_EVENT_MACHINE_NAME_CHANGEThe name of the device has changed

I have created a class simple named Core for declaring platform invoked methods from the CoreDLL.dll library and declared the CeRunApAtEvent function within it. The following schedules the the windows calculator to start when the device comes out of the suspended state.

CoreDLL.CeRunAppAtEvent(@"\Windows\Calc.exe", (int)WhichEvent.NOTIFICATION_EVENT_DEVICE_CHANGE);

After that call the windows calculator will start every single time that the device is woken up. To prevent the calculator from starting up a second call is necessary.

CoreDLL.CeRunAppAtEvent(@"\Windows\Calc.exe", (int)WhichEvent.NOTIFICATION_EVENT_NONE);

Included with this article is an example application that can be used to cause an application to launch for various events. Originally this program would only register a program to start upon wakeup. But I’ve extended the program so that it can also start programs in response to other events. Note that by changing the value in the call to CERunAppAtEvent that you can use the program cause an executable to launch for bcause of some other event (such as a memory card being inserted or ActiveSync completing its synchronization).

WakeupStart.png

When a program is autostarted a string is passed to it through the command line indicating the event that started it. I’ve included a program named ShowCommandLine with the source code that does nothing more than display the command line arguments that it received. From the screen shot below you can see the command line argument that was received when the program was started upon connecting to a network connection.

ShowCommandLine.png

Preventing Multiple Instances

Normally the .Net framework will take care of ensuring that multiple instances of your program are not running. This doesn’t always work for programs that are started because of a system event. Several system events can be fired in rapid succession or the same event can be fired twice (for some odd reason the wakeup event is usually fired twice). The first time I tried scheduling the ShowCommandLine program to start on wakeup and another event I ended up with several instances of it running.

MultiInstance.png

To get around this I create an event object (using P/Invoke) before loading the form. If several instances of the program are started in rapid succession then the creation of the event will fail, and we can use this failure to know that the this is not the first instance of the program and immediatly unload it.

static void Main() {
    IntPtr eventHandle = IntPtr.Zero;
    const string ApplicationEventName = "ShowCommandLineEvent";
    //We will use this as our handle to
    //to ensure only one instance of the
    //program is started
    try     {
         //Try to create the event.  If the creation fails then it is
         //because another instance of this application is already
         //running. If another instance exists then this instance
         //should immediatly terminate.
         eventHandle = CoreDLL.CreateEvent(IntPtr.Zero, true, false, ApplicationEventName);
         int lastError = Marshal.GetLastWin32Error();
         //MessageBox.Show(String.Format("event handle {0}",eventHandle));
         if (0 == lastError)         {
             Application.Run(new Form1());
         }
     }
     finally     {
         //When the application is no longer running it should release the event
         if (eventHandle != IntPtr.Zero)
             CoreDLL.CloseHandle(eventHandle);
     }
 } 

When multiple instances of a program are created in this manner you may want to send a notification to the first instance of the program so that it can respond to the event.

What’s Next?

This article is largly the result of research I am doing in preperation for software solution that I plan to design. In the next part of my research I will develop a solution for making the phone respond to other events not exposed directly through the the CeRunAppAtEvent function.

History

  • 19 July 2008 – Initial Publication
  • 31 July 2008 – Added reference to SHCreateShortcut (Thanks Zoomesh!)

Auto-launching an Application on Windows Mobile

I submitted an article to codeproject.com a little over a month ago about automatically starting an application base on an event or a schedule. I posted the content of the article here.  To get the source code visit http://www.codeproject.com/script/Articles/Article.aspx?aid=27917

Introduction

Figuring out how to make an application automatically start up had long been a mystery to me. The information was scattered and a bit of research was needed to collect all of. During my research I placed all of my notes in a various documents and have decided to organize them into a single document and share with all. The information presented here was tested on Windows Mobile 5 and Windows Mobile 6 devices but can also be applied to several versions of Windows CE (The OS from which Windows Mobile is derived).

It’s possible to achieve similar functionality by making your own executable that watches system changes through the SystemState class and responding accordingly, but that would cause your program to have a larger footprint.

About the Code

The first methods of automatically starting a program are centered in what I will call configuration tasks; making shortcuts, registry entries, or placing files in specific locations. For these methods I do not provide code examples. Later within this article I discuss methods of automatically launching applications that are setup through code. For these methods I include example code within the article and full source attached to the article.

The code examples rely on some Win32 functions that are called through P/Invoke. Both code examples refer to a project named Win32 which contains the references to these functions. Additionally Win32 also contain a structure and an enumeration needed to properly pass information to the WinAPI functions. To run the code examples you will need a Windows Mobile device (or emulator) and Visual Studio 2008.

Remember that on Windows Mobile devices you should prevent more than one instance of your program from existing in memory (if a second instance is started it should notify the first instance and then immediatly terminate).

What is meant be “auto-start?”

When I use the phrase auto-start I use it to refer to the launching of any program based on an event (other than the user clicking on the program’s icon). A program can be automatically started in one of four ways.

  • A program on a memory card runs as soon as the card is inserted
  • A program is scheduled to start at a predetermined time
  • A program is launched in response to a system change
  • A program launches at device power up

AutoRun from a Memory Card

The user inserting a memory card can cause an application to launch in one of two ways. The memory card could have a program on it that launches upon insertion of the Windows Mobile device could start a program that is already present in its main storage in response to the memory card being inserted. The later would be implemented by registering an application to start on a system change (discussed later).

When a memory card is inserted into a Windows Mobile / Windows CE device the OS automatically looks in a certain folder for a program named Autorun.exe. If that program is found then it is immediately run. The folder in which the OS looks is going to depend on what type of processor that the device has. For an overwhelming majority of Windows Mobile devices that folder will be “/2577”. Here is a table of the possible folder names for other Windows CE devices.

Processor Folder Name
ARM 720 1824
Arm 820 2080
ARM 920 2336
ARM 7TDMI 70001
Hitachi SH3 10003
Hitachi SH3E 10004
Hitachi SH4 10005
Motorola 821 821
SH3 103
SH4 104
Strongarm 2577

f you already have an application on a memory card that you wanted to autorun.exe but you did not want to rename the executable or place it in this folder then you can always make a second executable whose purpose is to launch your first executable.

Startup Shortcut

A shortcut can be made to an application that you wish to startup automatically and placed in \Windows\StartUp. Use this method if you have a single executable that needs to be started that has no dependencies on other executables. The format of shortcuts on windows mobile devices is simple. It will always be in the form of 00#”<\program Files\path>” where 00 is replaced with the number of characters that appear after the ‘#’ sign, the ‘#’ is a delimiter, and then the complete path to the executable. The following is an example of a shortcut to Windows Media Player.

23#“\windows\wmplayer.exe”

You don’t have to manually create the shortcut though. There is a native API call SHCreateShortcut that will create a shortcut for you. The first argument is the full path to the shortcut to be created and the second arguement is the full path to the file to which the shortcut points.

Starting an Application at Bootup

For Windows Mobile devices the location for autostart entries is HKEY_LOCAL_MACHINE\Init. Unlike the startup entries on a desktop machine (which only require the path to the executable to start) the entries for Windows Mobile devices are a little more structured. There are two keys associated with an application that needs to start up automatically, a LaunchXX key and an optional DependXX key. The XX would be replaced with a number. This number is also called the sequence number The value of LaunchXX is a string value (REG_SZ) that contains the path to the executable to be started. The DependXX key is used to specify on what applications that the current application has dependencies (and thus in what order the applications must be launched). The DependXX key contains a list of word (2 bytes) values that contain the sequence number values of the required applications.

The following screenshot is of the registry on my Windows Mobile 5 phone. Launch21 refers to an application named “coldinit.” If we look at Depend21 we see that “coldinit.exe” has a dependency on an application identified by 0x14 (20 decimal). So “coldinit.exe” must be launched after the app identified in Launch20, “Device.exe.”

Screen shot of Windows Mobile Registry

Applications launched using this method must notify the application of successful startup by calling the SignalStarted(DWORD) function. This function is a native call. For C programs the header to this function is defined in Winbase.h and in the library Coredll.lib. Developers using managed code will need to P/Invoke this method. The functions only argument is the sequence number of the executable. The sequence number is passed to the application as its only command argument. Note that the sequence number is the only argument that the application will be able to receive through the command line arguments. Any other information that must be passed to the application should be passed through configuration files or registry keys.

Starting a Program at a Specified Time

The Windows CE / Windows Mobile OS contains functionality for automatically starting a program at a specified time. The functionality is available through a call to CeRunApAtTime from the CoreDLL library. As mentioned by Jim Wilson in many of his “How Do I” video post on MSDN, this function expects the start time to be specified in the WinAPI SystemTime structure instead of the DateTime structure (CeRunAppAtTime is an unmanaged function called using the platform invoke functionality). Converting a time from a DateTime to a SystemTime is not difficult; there are already WinAPI functions that do this for you. To make calling this function easier I have placed the following code in my Win32Helper class. I’ve also provided an overloaded function to allow the time to be passed as an offset from the current time with a TimeSpan object.

public static void RunAppAtTime(string applicationEvent, DateTime startTime) {     long fileTimeUTC = startTime.ToFileTime();     long fileTimeLocal = 0 ;     SystemTime systemStartTime = new SystemTime();     CoreDLL.FileTimeToLocalFileTime(ref fileTimeUTC, ref fileTimeLocal);     CoreDLL.FileTimeToSystemTime(ref fileTimeLocal, systemStartTime);     CoreDLL.CeRunAppAtTime(applicationEvent, systemStartTime); } public static void RunAppAtTime(      string applicationEvent,       TimeSpan timeDisplacement ) {     DateTime targetTime = DateTime.Now + timeDisplacement;     RunAppAtTime(applicationEvent, targetTime); }

Where applicationEvent is the full path to the application to start and startTime is the time at which the application should be executed. There’s also an overloaded version of the method that accepts a TimeSpan object instead of a DateTime if you wanted to specify the start time relative to the current time.

If an application were attempting to schedule itself to be restarted at a later time it will need to be able to pass it’s complete path. I used reflection to find that path.

Module[] m = this.GetType().Assembly.GetModules(); target = m[0].FullyQualifiedName;

Screenshot of timed start program

Running the Program because of a System Change

There are a number of system changes that can be used to trigger the execution of a program. The WinAPI function CeRunAppAtEvent is used to associate a program with an event. Once associated that program will be launched every single time that the event occurs! So you must also remember to disassociate the program with the event when you no longer want it to automatically start.

I have created the enumeration in the Win32 class named WhichEvent that contains the ID numbers for the events that can be used to trigger program execution.

When a program is started because of a change in system state a single argument is passed to the program to indicate the state change that triggered the programs execution. (I don’t discuss the details of how to do that here). For a complete list of the possible arguments see the example cod in AutoStartArgumentString.cs.

Enumeration Element Description
NOTIFICATION_EVENT_NONE Used to clear all events associated with a program
NOTIFICATION_EVENT_TIME_CHANGE
NOTIFICATION_EVENT_SYNC_END ActiveSync synchronization has completed on the device
NOTIFICATION_EVENT_ON_AC_POWER The unit’s charger is connected
NOTIFICATION_EVENT_OFF_AC_POWER The unit’s charger is disconnected
NOTIFICATION_EVENT_NET_CONNECT The device is connected to a network
NOTIFICATION_EVENT_NET_DISCONNECT The device is disconnected from a network
NOTIFICATION_EVENT_DEVICE_CHANGE A memory card or other device was inserted or removed
NOTIFICATION_EVENT_IR_DISCOVERED The device has detected another infrared device
NOTIFICATION_EVENT_RS232_DETECTED The device has been connected to an RS232 device
NOTIFICATION_EVENT_RESTORE_END A full restore of the device has completed
NOTIFICATION_EVENT_WAKEUP The device has come out of a suspended state
NOTIFICATION_EVENT_TZ_CHANGE The time zone of the device has changed
NOTIFICATION_EVENT_MACHINE_NAME_CHANGE The name of the device has changed

I have created a class simple named Core for declaring platform invoked methods from the CoreDLL.dll library and declared the CeRunApAtEvent function within it. The following schedules the the windows calculator to start when the device comes out of the suspended state.

CoreDLL.CeRunAppAtEvent(@"\Windows\Calc.exe", (int)WhichEvent.NOTIFICATION_EVENT_DEVICE_CHANGE);

After that call the windows calculator will start every single time that the device is woken up. To prevent the calculator from starting up a second call is necessary.

CoreDLL.CeRunAppAtEvent(@"\Windows\Calc.exe", (int)WhichEvent.NOTIFICATION_EVENT_NONE);

Included with this article is an example application that can be used to cause an application to launch for various events. Originally this program would only register a program to start upon wakeup. But I’ve extended the program so that it can also start programs in response to other events. Note that by changing the value in the call to CERunAppAtEvent that you can use the program cause an executable to launch for bcause of some other event (such as a memory card being inserted or ActiveSync completing its synchronization).

WakeupStart.png

When a program is autostarted a string is passed to it through the command line indicating the event that started it. I’ve included a program named ShowCommandLine with the source code that does nothing more than display the command line arguments that it received. From the screen shot below you can see the command line argument that was received when the program was started upon connecting to a network connection.

ShowCommandLine.png

Preventing Multiple Instances

Normally the .Net framework will take care of ensuring that multiple instances of your program are not running. This doesn’t always work for programs that are started because of a system event. Several system events can be fired in rapid succession or the same event can be fired twice (for some odd reason the wakeup event is usually fired twice). The first time I tried scheduling the ShowCommandLine program to start on wakeup and another event I ended up with several instances of it running.

MultiInstance.png

To get around this I create an event object (using P/Invoke) before loading the form. If several instances of the program are started in rapid succession then the creation of the event will fail, and we can use this failure to know that the this is not the first instance of the program and immediatly unload it.

static void Main() {     IntPtr eventHandle = IntPtr.Zero;     const string ApplicationEventName = "ShowCommandLineEvent";  //We will use this as our handle to                                                                   //to ensure only one instance of the                                                                  //program is started                 try     {         //Try to create the event.  If the creation fails then it is          //because another instance of this application is already          //running. If another instance exists then this instance         //should immediatly terminate.         eventHandle = CoreDLL.CreateEvent(IntPtr.Zero, true, false, ApplicationEventName);         int lastError = Marshal.GetLastWin32Error();         //MessageBox.Show(String.Format("event handle {0}",eventHandle));                  if (0 == lastError)         {             Application.Run(new Form1());         }     }     finally     {         //When the application is no longer running it should release the event         if (eventHandle != IntPtr.Zero)             CoreDLL.CloseHandle(eventHandle);     } }

When multiple instances of a program are created in this manner you may want to send a notification to the first instance of the program so that it can respond to the event.

 

 

What’s Next?

This article is largly the result of research I am doing in preperation for software solution that I plan to design. In the next part of my research I will develop a solution for making the phone respond to other events not exposed directly through the the CeRunAppAtEvent function.

History

  • 19 July 2008 – Initial Publication
  • 31 July 2008 – Added reference to SHCreateShortcut (Thanks Zoomesh!)

Geo-tagging Images

 Roi y Zysman made an entry on his blog about geotagging jpgs images with a few lines of code in C#.   Very useful.  Takn directly from his site:

 

 appears that it is very simple to read and write these GPS settings from within the JPEG image using .Net’s System.Drawing.Image class.
The data stored in JPEG images complies with the EXIF data format. We can use the Image class to read and write data from and to the JPEG image.
here is an example:
Image Pic = Image.FromFile(Filename);  PropertyItems = Pic.PropertyItems;  PropertyItems[0].Id = 0x0002; //index of the EXIF TAG  PropertyItems[0].Type = 5;//  PropertyItems[0].Len = length;  PropertyItems[0].Value =new byte[length];  Pic.SetPropertyItem(PropertyItems[0]);

And that’s pretty much it, there are a few more tweaks to save the image.
I’m publishing here a small C# file with a static function to perform a simple action to embed GPS latitude, longitude (Which can be taken from the gps log according to time that the picture was taken).
It is pretty much straight forward.
It can be used like so

WriteLongLat(“c:/temp/house_gps.jpg”, 33, 0, 48.46, 35, 5, 38.12);

where the first parameter represents the file name to be embedded and the other parameters represent the lon and lat degrees, minutes, and seconds..
Feel free to use this as will (LGPL) license

Your Device is Showing

I had noticed this some time ago but didn’t think much of it, but a few users are a little upset to discover that their Treos are visible on the Sprint network using Resco Explorer 2008.  They are attributing the visibility to some flaw in the Sprint network.  The “flaw” is not specific to the Sprint network or the Treo.  I can do the same thing on the AT&T network and shortly should be able to verify that I can do it on the T-Mobile network.  Does this pose any security threats?  I don’t know.  I don’t have any services that I know of listening to ports on my phone. If all goes well, I should be able to examine my phone in detail sometime this week to see if anything is listening.

“Spark Your Imagination”

As I delve more deeply into mobile development I am considering changing my attention from Windows Mobile Professional to Windows CE  But wait, aren’t those the same things?  No.

What’s the Difference in Windows CE and Windows Mobile

Windows C.E. is a modular embedded operating system.  Developers using Windows CE can can select from a set of of modular components that meet their needs to configure a Windows CE image for their solution.  Windows Mobile is derived from Windows CE.  Windows Mobile is also modular in nature.  OEMs building a Windows Mobile device have a set of core functionality and components that must be installed and then can choose and select from a set of modular components.  They can also add features that don’t exists in the Windows Mobile API.

I have several Windows Mobile devices running Windows 2003 SE, Windows Mobile 5 Professional, and Windows Mobile 6 Professional.  While these serve as nice testing hardware test devices the APIs available to them are more limited.  Windows CE has more potential flexibility.  Acquiring a Windows CE hardware testing platform will be easier than I thought it to be.  Microsoft has a program with their partners called Spark your Imagination to assist developers in acquiring CE hardware  for non-commercial projects.  Some of the features of the kits available through this program are

  • Professional-grade product at an affordable-grade product at an affordable price
  • Support for up to 32,000 simultaneous processes
  • 2 GB of virtual memory space for each process
  • Native real-time OS

I would like to purchase a kit promptly, but I will wait at least three weeks before making a decision so that I can make an informed decision.