onsdag 7 oktober 2009

CeRunAppAtTime - using CSharp

Some time ago, I needed to run Windows Mobile based application at a specific interval. No sweat - Windows CE offers excellent scheduler API's; CeRunAppAtTime among others.
The catch however was that I had to implement it in CSharp.

CeRunAppAtTime is a simple API that takes two parameters. One string containing that path to the executable and one instance of SYSTEMTIME that specifies the date and time to execute the application.

Here is the CSharp implementation of the SYSTEMTIME struct. Notice that I've implemented it as a class and that the constructor converts a .Net DateTime to the corresponding SYSTEMTIME.

    [StructLayout(LayoutKind.Sequential)]
public class SYSTEMTIME
{
public ushort wYear;
public ushort wMonth;
public ushort wDayOfWeek;
public ushort wDay;
public ushort wHour;
public ushort wMinute;
public ushort wSecond;
public ushort wMilliseconds;

public SYSTEMTIME(DateTime dtDateTime)
{
this.wYear = (ushort)dtDateTime.Year;
this.wMonth = (ushort)dtDateTime.Month;
this.wDayOfWeek = (ushort)dtDateTime.DayOfWeek;
this.wDay = (ushort)dtDateTime.Day;
this.wHour = (ushort)dtDateTime.Hour;
this.wMinute = (ushort)dtDateTime.Minute;
this.wSecond = (ushort)dtDateTime.Second;
this.wMilliseconds = 0;
}
}


The DllImport declaration of CeRunAppAtTime is as follows:
        [DllImport("CoreDLL.dll", SetLastError = false, EntryPoint="CeRunAppAtTime")]
public extern static bool RunAppAtTime(string AppName, SYSTEMTIME SysTime);


To schedule an application for execution simply do the following:
            DateTime dtStart = DateTime.Now;
dtStart = dtStart.AddMinutes(2);
SYSTEMTIME sysTime = new SYSTEMTIME(dtStart);
if (Notify.Notify.RunAppAtTime(@"\windows\bubblebreaker.exe", sysTime))
MessageBox.Show("Successfully scheduled Bubble Breaker for execution at: " + dtStart.ToShortTimeString());
else
MessageBox.Show("Failed to schedule Bubble Breaker for execution.");

Bonus trick:
To cancel the execution of a scheduled application simply call CeRunAppAtTime with the same application path but pass a null-value instead of a SYSTEMTIME struct.
Ex.
        public static bool CancelRunAppAtTime(string AppName)
{
return RunAppAtTime(AppName, null);
}


Tomorrow we'll look at CeRunAppAtEvent.

Enjoy

Inga kommentarer:

Skicka en kommentar