Search

Wednesday, February 16, 2011

detect timezone change in .NETcf C#?

recently while developing a windows mobile application i came across a major blocker that is once the application is started if in between user changes the device / system time zone the application was returning the old timezone itself that is the timezone of the device at the application startup, since i was running my app as the background service it was a major blocker for me.

then i came to know that compact framework actually caches timezone at startup and timezone changes in between is not detected and notified by framework to the application unless and until we restart the application.

Is there any hack so that we can get the latest timezone notifications?
yes, it can be done using P/Invoke CeRunAppAtEvent and catch the notification events fired by the system when timezone changes below is the sample code found in one of the forum i tried it this worked for me
[DllImport("coredll.dll", EntryPoint = "CreateEvent", SetLastError = true)]
private static extern IntPtr CreateEvent(IntPtr lpEventAttributes,
bool bManualReset,
bool bInitialState, string spName);

[DllImport("coredll.dll", EntryPoint = "WaitForSingleObject",
SetLastError = true)]
private static extern int WaitForSingleObject(IntPtr hHandle, UInt32
dwMilliseconds);

[DllImport("coredll.dll", EntryPoint = "CloseHandle", SetLastError =
true)]
private static extern bool CloseHandle(IntPtr hHandle);

[DllImport("coredll.dll", EntryPoint = "CeRunAppAtEvent",
SetLastError = true)]
private static extern bool CeRunAppAtEvent(string pszAppName, long
lwichEvent);

private const int NOTIFICATION_EVENT_TIME_CHANGE = 1;
private const UInt32 INFINITE = 0xFFFFFFFF;

public Form1()
{
InitializeComponent();


CeRunAppAtEvent("\\\\.\\Notifications\\NamedEvents \\MyTimeNamedEvent",
NOTIFICATION_EVENT_TIME_CHANGE);

Thread thread = new Thread(new ThreadStart(ThreadProc));
thread.Start();
}

private void ThreadProc()
{
IntPtr hEvent = CreateEvent(IntPtr.Zero, false, false,
"MyTimeNamedEvent");

WaitForSingleObject(hEvent, INFINITE);

MessageBox.Show("Time Event Occured");

CloseHandle(hEvent);
}
though i did not get any direct api to detect the change in timezone apart from these win32 hack, if you know any other simple way to do it please let us know, once you get the timezone change event just restart your application or write appropriate code which suits your needs to cope with timezone change in my application i wrote separate small app to detect tZ change and i was sending a notification via inter process communication and restarting the service to adapt to new timezone.

1 comments:

Prasad said...

Is there a way to handle time zone change event in windows service. I am facing the similar issue as :(

Post a Comment

Other Interesting Articles



Related Article Widget by Yogith

Search Powered by Google