little coding help needed - Windows Mobile Development and Hacking General

hey folks,
here's what I wanna do:
I need a program that runs in the background and checks if my mda2 is in the cradle or not. if it's plugged in the cradle I want it to change in my connection settings from work to internet. I need this for the following reason: my cellphone provider only offers grps over a proxy and that proxy wount work in the cralde when I share my PC connection via active sync. so right now I always need to switch between work and internet connection by myself.
I only know visual basic so I guess I need to take a look at eVB.
Is such a tool even possible in eVB? if so, where would I start? can someone point me in the right direction? maybe give me some links for research.
thanks for your help in advance
cyas

ait, did some research.
looks like just turning the proxy off should do the trick.
I tried doing this via the registry.
for now I just wanted to read out a key. this is what I got so far:
Code:
Option Explicit
Public Declare Function RegOpenKeyEx Lib "Coredll" Alias "RegOpenKeyExW" (ByVal hKey As Long, ByVal lpSubKey As String, ByVal ulOptions As Long, ByVal samDesired As Long, phkResult As Long) As Long
Public Declare Function RegQueryValueEx Lib "Coredll" Alias "RegQueryValueExW" (ByVal hKey As Long, ByVal lpValueName As String, ByVal lpReserved As Long, lpType As Long, ByVal lpData As String, lpcbData As Long) As Long
Public Declare Function RegCloseKey Lib "Coredll" (ByVal hKey As Long) As Long
Const ERROR_SUCCESS = &O0
Const HKEY_LOCAL_MACHINE = &H80000001
Private Sub Command1_Click()
Dim lngSize As Long, hlngSubKey As Long
Dim lngType As Long, lngResult As Long
Dim RegData As Integer
lngSize = 256
RegData = String(lngSize, 0)
lngResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "\SOFTWARE\Microsoft\ConnMgr\Providers\{EF097F4C-DC4B-4c98-8FF6-AEF805DC0E8E}\HTTP-{18AD9FBD-F716-ACB6-FD8A-1965DB95B814}", 0, 0, hlngSubKey)
lngResult = RegQueryValueEx(hlngSubKey, "Proxy", 0, lngType, RegData, lngSize)
MsgBox RegData, vbOKOnly, "o2 proxy"
lngResult = RegCloseKey(hlngSubKey)
End Sub
Private Sub Form_OKClick()
App.End
End Sub
unfortunately when I press the button I only get a blank window. it wount show the proxy.
can someone tell me what I'm doing wrong?
oh and I still dont know how I could detect wether there is an active sync connection open or not. any ideas on that?

uhm, no one here who knows some eVB?

_4saken_ said:
Dim RegData As Integer
Click to expand...
Click to collapse
RegData should be declared as
Code:
Dim RegData As String

thanks for the answer but changing it to string didnt help. I still get an empty msg box.
any other ideas what I'm doing wrong?

Related

I Developed my first Application.... here it is

Hi to u all
i have developed my first application for XDA
BMI Calculator
its working fine on my computer, its installing to my xda as well but BIG BUT
i am not able to input in textfields in other words i am not able to open my keyboard
can any one help me on this i am using VB .NET to make it.
i think i have to make a focus or something on textfields i do no how to do that plz help
Regards
GUGI
i'm learning c++, no idea about .net, but in c++ when you receive the focus message from the text box, you show the sip using the api commands. don't have any code in front of me right now, check msdn.
V
thanx Vijay
let me try then i let u guys know
Regards
Gugi
Hi to u all
I have no luck to find the solution for my prob, so anyone help me plz
Regards
Gugi
gugi_sat said:
Hi to u all
I have no luck to find the solution for my prob, so anyone help me plz
Regards
Gugi
Click to expand...
Click to collapse
1: Add a inputpanel to your form.
2: Set the inputpanel's Enabled property to False.
3: Add Inputpanel1.Enabled = true in the textbox's GotFocus Event.
4: Add InputPanel1.Enabled = false in then textox's LostFocus Event.
hi there
i will give it try
Thnx
Regrads
Gugi
hi GeirFrimann
i tried the code u told me
but i am getting the System.exception when i click on the txtfield in deployment
then i put the code like this
Code:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
Application.Exit()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAbout.Click
Dim company As String
Dim about As String
Dim version As String
company = "Gugi's Software"
about = "BMI Calculator"
version = "v1.0 beta"
MessageBox.Show(company & vbNewLine & about & vbNewLine & version, "About...")
End Sub
Private Sub btnCal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCal.Click
Dim height As Double
Dim weight As Double
Dim bmi As Double
height = txtHeight.Text
weight = txtWeight.Text
Try
bmi = weight / ((height / 100) * (height / 100))
Catch c As Exception
If (bmi < 18.4) Then
MessageBox.Show(bmi.ToString & vbNewLine & "Your are UNDERWEIGHT", "Your BMI...")
ElseIf (bmi > 18.5 And bmi < 24.9) Then
MessageBox.Show(bmi.ToString & vbNewLine & "Your are NORMAL", "Your BMI...")
ElseIf (bmi < 25 And bmi > 29.9) Then
MessageBox.Show(bmi.ToString & vbNewLine & "Your are OVERWEIGHT", "Your BMI...")
ElseIf (bmi > 30) Then
MessageBox.Show(bmi.ToString & vbNewLine & "Your are OBESE", "Your BMI...")
End If
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MessageBox.Show("Please Enter your height in Centimeters", "Height?")
End Sub
Private Sub Button2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
MessageBox.Show("Please Enter your Weight in Kilogrames", "Weight?")
End Sub
Private Sub txtHeight_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtHeight.GotFocus
Try
InputPanel1.Enabled = True
Catch ex As Exception
End Try
End Sub
Private Sub txtHeight_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtHeight.LostFocus
Try
InputPanel1.Enabled = False
Catch ex As Exception
End Try
End Sub
Private Sub txtWeight_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtWeight.GotFocus
Try
InputPanel2.Enabled = True
Catch ex As Exception
End Try
End Sub
Private Sub txtWeight_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtWeight.LostFocus
Try
InputPanel2.Enabled = False
Catch ex As Exception
End Try
End Sub
End Class
plz help
Regards
Gugi[/code]
gugi_sat said:
hi GeirFrimann
i tried the code u told me
but i am getting the System.exception when i click on the txtfield in deployment
then i put the code like this
Click to expand...
Click to collapse
Any details on exception message?
Probably something wrong with variable name InputPanel1 or InputPanel2. There must be one input panel declared per form. So, declare variable "sip" using "private Microsoft.WindowsCE.Forms.InputPanel" notation and use it to hide/show Input Panel.
Cheers
Hi IMate->WM2k5
Thanx for reply its working its the bug in my try catch satatement in the calculation method
any way with both of your help i am able to make this posible
thanx for that here is the new woring cab file please try this and let me know how it goes
another thing i need to ask is there any tutotial or book for vb .net developement for pocket pc plz let me know
Regards
Gugi
Hi to you all
Here is the latest version with almost all the fixed errors
well if you find something plz let me know
Regrads
Gugi
hi to you all
plz give me some feed back so that i can improve this and develope something else
Regards
Gugi

Problem creating Registry Keys - VB.NET CF 1.x

Hi, if i create a registry key i get an NonSupportet Exception.
Can someone Help?
Here the important part of my code:
Code:
Public Const HKEY_CURRENT_USER = &H80000001
Public Const HKEY_LOCAL_MACHINE = &H80000002
Public Const KEY_ALL_ACCESS = &H3F
Public Const REG_OPTION_NON_VOLATILE = 0
Private Declare Function RegCreateKeyEx Lib "coredll.dll" Alias "RegCreateKeyExW" ( _
ByVal hkey As Long, _
ByVal lpSubKey As String, _
ByVal Reserved As Long, _
ByVal lpClass As String, _
ByVal dwOptions As Long, _
ByVal samDesired As Long, _
ByVal lpSecurityAttributes As Long, _
ByRef phkResult As Long, _
ByRef lpdwDisposition As Long) As Long
Public Shared Function CreateNewKey(ByVal lSection As Long, _
ByVal sNewKeyName As String) As Long
Dim hNewKey As Long
Dim lRetVal As Long
RegCloseKey(lSection)
--HERE--> lRetVal = RegCreateKeyEx(lSection, sNewKeyName, 0, _
vbNullString, REG_OPTION_NON_VOLATILE, _
KEY_ALL_ACCESS, _
0, hNewKey, lRetVal)
CreateNewKey = hNewKey
RegCloseKey(hNewKey)
End Function
...
i call for example:
CreateNewKey(HKEY_LOCAL_MACHINE, "SOFTWARE\Microsoft\Today\Items\""Wireless""" )
Please help.
Thanks.
BongoUser said:
Hi, if i create a registry key i get an NonSupportet Exception.
Can someone Help?
Here the important part of my code:
Code:
Public Const HKEY_CURRENT_USER = &H80000001
Public Const HKEY_LOCAL_MACHINE = &H80000002
Public Const KEY_ALL_ACCESS = &H3F
Public Const REG_OPTION_NON_VOLATILE = 0
Private Declare Function RegCreateKeyEx Lib "coredll.dll" Alias "RegCreateKeyExW" ( _
ByVal hkey As Long, _
ByVal lpSubKey As String, _
ByVal Reserved As Long, _
ByVal lpClass As String, _
ByVal dwOptions As Long, _
ByVal samDesired As Long, _
ByVal lpSecurityAttributes As Long, _
ByRef phkResult As Long, _
ByRef lpdwDisposition As Long) As Long
Public Shared Function CreateNewKey(ByVal lSection As Long, _
ByVal sNewKeyName As String) As Long
Dim hNewKey As Long
Dim lRetVal As Long
RegCloseKey(lSection)
--HERE--> lRetVal = RegCreateKeyEx(lSection, sNewKeyName, 0, _
vbNullString, REG_OPTION_NON_VOLATILE, _
KEY_ALL_ACCESS, _
0, hNewKey, lRetVal)
CreateNewKey = hNewKey
RegCloseKey(hNewKey)
End Function
...
i call for example:
CreateNewKey(HKEY_LOCAL_MACHINE, "SOFTWARE\Microsoft\Today\Items\""Wireless""" )
Please help.
Thanks.
Click to expand...
Click to collapse
Hi,
1) I wouldn't use lRetVal for the last parameter and the return function value. The last parameter returns the disposition value and the function return value returns 0 for success or an error that you can find in WINERROR.H and so in MSDN documentation.
If it is not the problem then:
2) In place of trying to create a key in HKLM, try first in HKCU, maybe the problem doesn't reside in the code but in the fact that you are trying to create a key in HKLM where you need "authorization" to do it. Your application needs to have privileges like being signed.
Hope it helps,
Cheers,
.Fred
ps.: use a real program language like C/C++. VB is crap!!!
dotfred said:
Hi,
1) I wouldn't use lRetVal for the last parameter and the return function value. The last parameter returns the disposition value and the function return value returns 0 for success or an error that you can find in WINERROR.H and so in MSDN documentation.
If it is not the problem then:
2) In place of trying to create a key in HKLM, try first in HKCU, maybe the problem doesn't reside in the code but in the fact that you are trying to create a key in HKLM where you need "authorization" to do it. Your application needs to have privileges like being signed.
Hope it helps,
Cheers,
.Fred
ps.: use a real program language like C/C++. VB is crap!!!
Click to expand...
Click to collapse
Hi,
it works nowm thanks.
I have found a working sample in www.

timer in vb.net cf

I am trying to create a simple stopwatch like app and am having a hard time figuring it out.
in vb.net i can simply use Timer.Start() or Timer.Stop()
This will not work in the .net cf though. I googled the topic for over an hour and did a quick search on the forum and found no result.
Can anyone help me with a way around this, there has to be something simple I am missing or another way to do it. I just need a timer i can start, stop, pause and resume.
Thanks in advance.
Set the timer's Enabled property to true/false.
that works to start and stop it but if i want to pause and then resume it starts from the very begging instead of where it was paused.
ex: pause after 10sec. wait 10sec and hit resume....the timer jumps to 20sec instead of going to 11sec
Why not increment a variable when the timer ticks? Post some sample code here and we could help you debug it....
Do the calculations by using DateTime and TimeSpan.
Code:
Public Class Form1
Dim startTime As DateTime
Private Sub Timer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer.Tick
Dim span As TimeSpan = DateTime.Now.Subtract(startTime)
lblTimer.Text = span.Hours.ToString & ":" & span.Minutes.ToString & ":" & span.Seconds.ToString
btnStop.Enabled = True
btnPause.Enabled = True
End Sub
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
startTime = DateTime.Now()
Timer.Start()
If (Timer.Enabled = True) Then
btnStart.Text = "Restart"
End If
End Sub
Private Sub btnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStop.Click
If (Timer.Enabled) Then
Timer.Stop()
End If
End Sub
Private Sub btnPause_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPause.Click
If (Timer.Enabled) Then
Timer.Stop()
btnPause.Text = ("Resume")
Else : Timer.Start()
btnPause.Text = ("Pause")
End If
End Sub
End Class
now the problem is timer.start and timer.stop do not work as they are not included in the cf
I code in C#, but don't you need to declare a variable of type Timer to use it? I don't think there are any static methods for the Timer class.
the above code works fine in the standard .net framework but the start and stop methods are not in the compact framework so i need to find a way around that
Sorry, I got confused with the naming conventions - I thought Timer was a class reference.
Start and Stop works in the full framework, but the logic of your code is wrong - you are always subtracting the _start_ time from the current time when the timer ticks. This is why when you resume, it's still counting how many seconds has passed since you pressed Start.
This should work:
Code:
Public Class Form1
Dim startTime As DateTime
Dim span As TimeSpan
Dim hours, minutes, seconds As Integer
Private Sub Timer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer.Tick
span = DateTime.Now.Subtract(startTime)
lblTimer.Text = span.Hours.ToString & ":" & span.Minutes.ToString & ":" & span.Seconds.ToString
End Sub
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
startTime = DateTime.Now()
Timer.Enabled = True
If (Timer.Enabled = True) Then
btnStart.Text = "Restart"
End If
End Sub
Private Sub btnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStop.Click
Timer.Enabled = False
End Sub
Private Sub btnPause_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPause.Click
If (Timer.Enabled) Then
Timer.Enabled = False
btnPause.Text = ("Resume")
hours = span.Hours
minutes = span.Minutes
seconds = span.Seconds
Else
startTime = DateTime.Now.Subtract(New TimeSpan(hours, minutes, seconds))
Timer.Enabled = True
btnPause.Text = ("Pause")
End If
End Sub
End Class
Man, coding in VB brings back memories...
...i see your point thanks a lot...as soon as i am done backing the hard drive up in my msi wind i will give this a shot...thanks again

Hiding/showing a form (vb.net)

I am trying to replace my contacts program with one I wrote myself but I'm having a little problem getting the form to hide and then show again?
I would like to start my app from a button, easy enough but I'm a little confused with hiding it again. I can hide the form but if I press the button again nothing happens but I'd like my app to show itself again?
Could someone please help the village idiot and point me in the right direction please?
Ok solved my problem. I used another exe to boot the program and if it was already booted then show the program via the API.
Imports System.Runtime.InteropServices
Imports System.Diagnostics
Module ModMain
<DllImport("coredll")> _
Public Function FindWindow(ByVal lpClass As String, ByVal lpTitle As String) As IntPtr
End Function
<DllImport("CoreDll")> _
Public Function ShowWindow(ByVal hwnd As IntPtr, ByVal nCmdShow As Integer) As Boolean
End Function
<DllImport("CoreDll")> _
Public Function SetForegroundWindow(ByVal hWnd As IntPtr) As Boolean
End Function
Const SW_HIDE As Integer = 0
Const SW_SHOW As Integer = 5
Public Sub Main()
Dim hWnd As Long = FindWindow("#NETCF_AGL_BASE_", "Contacts")
If hWnd = IntPtr.Zero Then
Dim AP As New Process
AP.StartInfo.FileName = "Program Files\ContactsList2\ContactsList2.exe"
AP.Start()
Else
ShowWindow(hWnd, SW_SHOW)
SetForegroundWindow(hWnd)
End If
End Sub
End Module

Set Device Time from Server

Hi,
Does anybody know how to pull the time from a server and use that time to update the devices clock?
I want to lock the Clock down on the device so the best way to ensure the time is correct is to sync it with a server.
I'm using VB.net.
Give this a spin.
It sets the get the UTC time, from http://www.timeapi.org/ , but have a look at the site to see what else it can do.
Your device should deal with your timezone offset from UTC automatically.
I used .NET Reflector to translate into VB from C#, hence the odd definition of some variables.
Code:
Public Structure SYSTEMTIME
Public wYear As UInt16
Public wMonth As UInt16
Public wDayOfWeek As UInt16
Public wDay As UInt16
Public wHour As UInt16
Public wMinute As UInt16
Public wSecond As UInt16
Public wMilliseconds As UInt16
End Structure
Declare Function GetSystemTime Lib "CoreDll.dll" _
(ByRef lpSystemTime As SYSTEMTIME) As UInt32
Declare Function SetSystemTime Lib "CoreDll.dll" _
(ByRef lpSystemTime As SYSTEMTIME) As UInt32
Private Shared Sub Main(ByVal args As String())
Dim Buffer As Byte() = New Byte(&H19 - 1) {}
Dim DateItems As String() = New String(8 - 1) {}
Dim Separators As Char() = New Char() { "-"c, "-"c, "T"c, ":"c, ":"c, "+"c, ":"c }
Dim Now As New SYSTEMTIME
Program.GetSystemTime((Now))
Dim ResponseStream As Stream = WebRequest.Create("http://www.timeapi.org/utc/now").GetResponse.GetResponseStream
ResponseStream.Read(Buffer, 0, &H19)
ResponseStream.Close
DateItems = Encoding.UTF8.GetString(Buffer, 0, &H19).Split(Separators)
Now.wYear = Convert.ToUInt16(DateItems(0))
Now.wMonth = Convert.ToUInt16(DateItems(1))
Now.wDay = Convert.ToUInt16(DateItems(2))
Now.wHour = Convert.ToUInt16(DateItems(3))
Now.wMinute = Convert.ToUInt16(DateItems(4))
Now.wSecond = Convert.ToUInt16(DateItems(5))
Now.wMilliseconds = 0
Program.SetSystemTime((Now))
End Sub
The original C# code is here. You will have to convert the C# 'using' statements to VB 'Imports'
Code:
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
namespace GetTime
{
class Program
{
[DllImport("coredll.dll")]
private extern static void GetSystemTime(ref SYSTEMTIME lpSystemTime);
[DllImport("coredll.dll")]
private extern static uint SetSystemTime(ref SYSTEMTIME lpSystemTime);
private struct 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;
}
static void Main(string[] args)
{
byte[] Buffer = new byte[25];
string DateString;
string[] DateItems = new string[8];
char[] Separators = new char[7] { '-', '-', 'T', ':', ':', '+', ':' };
SYSTEMTIME Now = new SYSTEMTIME();
GetSystemTime(ref Now);
Stream ResponseStream = WebRequest.Create("http://www.timeapi.org/utc/now").GetResponse().GetResponseStream();
ResponseStream.Read(Buffer, 0, 25);
ResponseStream.Close();
DateString = Encoding.UTF8.GetString(Buffer, 0, 25);
DateItems = DateString.Split(Separators);
Now.wYear = Convert.ToUInt16(DateItems[0]);
Now.wMonth = Convert.ToUInt16(DateItems[1]);
Now.wDay = Convert.ToUInt16(DateItems[2]);
Now.wHour = Convert.ToUInt16(DateItems[3]);
Now.wMinute = Convert.ToUInt16(DateItems[4]);
Now.wSecond = Convert.ToUInt16(DateItems[5]);
Now.wMilliseconds = 0;
SetSystemTime(ref Now);
}
}
}
Here's how it works: The call to the URL returns the date/time as a char buffer.
"2011-12-02T14:56:38+00:00" as an example.
After converting this to a string we convert it into an array of strings in DateItems[] as
2011
12
02
14
56
38
00
00
using Separators[] to split the fields apart.
These are then converted to ushort values in the time structure, before setting the time on the device with it.
Nice code stephj .
Cheers!!!
Thanks for that stephj, will give it a go.
i've tried this and i'm getting a :
The remote server returned an error: (407) Proxy Authentication Required.
any ideas?
I tried the above program on an emulated device connected to the net via its host PC's connection and it worked a treat.
To get through a proxy, you will need to add the following code.
Code:
Program.GetSystemTime((Now))
**************INSERT THIS ****************
Dim Proxy as new WebProxy("http://ProxyServer:80/",true)
proxy.Credentials = CredentialCache.DefaultCredentials
WebRequest.DefaultWebProxy = proxy
**************INSERT ENDS ****************
Dim ResponseStream As Stream = WebRequest.Create("http://www.timeapi.org/utc/now").GetResponse.GetResponseStream
Where the first parameter of the WebProxy constructor is the name of your proxy server, and the port it uses. Here at work, we can get away with just using our proxy server's internal network DNS name of "Internet:8080", to access the outside web through a Microsoft ISA Proxy/Firewall. Note in this case the proxy uses a different port number of 8080 as opposed to the default http port of 80. If yours is not 80 you will have to provide it. You may have to do some groundwork to track down the name of your proxy server, and the port it uses. I would start by looking at the proxy setup in Settings->Connections->'Set up my proxy server' for starters.
CredentialCache.DefaultCredentials, picks up your default login/credentials and passes them to the proxy server. If it works properly, you should go through it, seamlessly.
Good luck!
Hi steph,
i tweaked this slightly and set up a webreference in my program, i then pull the time down from that in the format of "2011-12-12T09:43:14", it then splits it.
The problem i am having is that sometimes it seems to add an hour to the time.
Any ideas?
What time zone is your device operating under?
Start->Settings->[System]->Clock & Alarms->[Time]
What's the zone, and is it Home or Visiting? - I'll see if I can duplicate it.
GMT London and is set as Home.
As a test I set the time on the device to: 01/06/1999 and time 01:00:00. When i run the program the first time i press my 'Update Time' button and it returns 12/12/11 and 12:53:04, so 1 hour ahead. If i press the button again I get the correct time.
I notice on your original post that the time returned had +00:00 on the end but you dont seem to use it when you break the string down, is this not required?
Thanks for the help, much appreciated
At least I can duplicate it, so that is a start. It only seems to throw the hour forward if the date has changed, which explains why the second call to it corrects the time.
If you just knock the time back a couple of hours, a single call of the program sets the correct time.
Interesting. I'll try and get to the bottom of it, might take a day or so, on and off.
Edit: Got it!
The 1st of June 1999 is in BST one hour in front of GMT/UTC. The first call changes the date and time using BST, leaving the time pushed forward one hour. The date is then set to today's date which is in GMT/UTC. The second call sets the time against the GMT Timezone which corrects the time.
Set the date time to 04:00 yesterday and it works fine.
I'll see if we can fix it a bit better. More later.........
Here's the cure: It's C#, I'll leave you to convert it to VB.
The secret is to set the time twice, but stall the thread for ten seconds inbetween. The device will sort itself out in the gap, as various time and date housekeeping tasks are triggered. The second SetTime(), will carry out the final fix of the time before the program finally ends.
This should also work in BST when changing from a GMT/UTC date, and should also work with all global time zones.
Add this:
Code:
using System.Threading;
SetSystemTime(ref Now);
Thread.Sleep(10000);
SetSystemTime(ref Now);
that's great steph, thanks again.
There is a minor problem with the previous code:- If the minute happens to roll over in the 10 seconds while the process is asleep, then the change of minute will be lost.
Here's a better solution. Create a DateTime object in which to store the returned date and time from the WebRequest().
Use it to set the system date/time, and then advance it forward ten seconds.
Set the date/time with it again, after the ten second sleep() has elapsed.
Seems to work O.K. Post bug reports to this thread, if you find it doesn't.
Code:
using System;
using System.Net;
using System.Text;
using System.Threading;
using System.IO;
using System.Runtime.InteropServices;
namespace GetTime
{
class Program
{
[DllImport("coredll.dll")]
private extern static uint SetSystemTime(ref SYSTEMTIME lpSystemTime);
private struct 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;
}
static void Main(string[] args)
{
byte[] Buffer = new byte[25];
string DateString;
string[] DateItems = new string[8];
char[] Separators = new char[7] { '-', '-', 'T', ':', ':', '+', ':' };
SYSTEMTIME Now = new SYSTEMTIME();
Stream ResponseStream = WebRequest.Create("http://www.timeapi.org/utc/now").GetResponse().GetResponseStream();
ResponseStream.Read(Buffer, 0, 25);
ResponseStream.Close();
DateString = Encoding.UTF8.GetString(Buffer, 0, 25);
DateItems = DateString.Split(Separators);
DateTime SaveTime = new DateTime(Convert.ToInt32(DateItems[0]),Convert.ToInt32(DateItems[1]),Convert.ToInt32(DateItems[2]),Convert.ToInt32(DateItems[3]),Convert.ToInt32(DateItems[4]),Convert.ToInt32(DateItems[5]));
Now.wYear = Convert.ToUInt16(SaveTime.Year);
Now.wMonth = Convert.ToUInt16(SaveTime.Month);
Now.wDay = Convert.ToUInt16(SaveTime.Day);
Now.wHour = Convert.ToUInt16(SaveTime.Hour);
Now.wMinute = Convert.ToUInt16(SaveTime.Minute);
Now.wSecond = Convert.ToUInt16(SaveTime.Second);
Now.wMilliseconds = 0;
SetSystemTime(ref Now);
SaveTime.AddSeconds(10);
Thread.Sleep(10000);
Now.wYear = Convert.ToUInt16(SaveTime.Year);
Now.wMonth = Convert.ToUInt16(SaveTime.Month);
Now.wDay = Convert.ToUInt16(SaveTime.Day);
Now.wHour = Convert.ToUInt16(SaveTime.Hour);
Now.wMinute = Convert.ToUInt16(SaveTime.Minute);
Now.wSecond = Convert.ToUInt16(SaveTime.Second);
SetSystemTime(ref Now);
}
}
}
C# .NET CF 2.0 WinMo 5.0 onwards executable is included in the zip file.
It is a console application, so don't expect anything much to happen until the 'hourglass' disappears.
If the first SetSystemTime() ends up changing the date across a Daylight Saving Boundary date, then, during the sleep() period, the device's housekeeping date/time/alarm services will probably retrigger any outstanding task and event reminders for 'today'.
P.S. GetSystemTime() can be dropped it is not required.
works like a charm steph, nice one. thanks.
@stephj, Thanks for the updated code .
Cheers!!!
Seem to be having a problem with this since UK has put the clocks forward an hour, every time I update using this code my device is adding an hour to the time.
The device is an M3 Mobile.
What are the settings on the Start-> Settings->Clock and Alarms->Time[Tab]
It should still have the Home radio button active and the time zone set to GMT London, Dublin. The mobile device should take care of daylight saving itself.
Is your M3 running WinMo 6.1 or 6.5? But I can't see it making much difference.
Works OK on a stock 6.1 Kaiser (Vodafone v1615)
Update: Also seems to work OK on the WM 6.5.3 Professional emulator.
wubbledoos said:
Hi,
Does anybody know how to pull the time from a server and use that time to update the devices clock?
I want to lock the Clock down on the device so the best way to ensure the time is correct is to sync it with a server.
I'm using VB.net.
Click to expand...
Click to collapse
Well on my Kaisers (running either wm 6.1 or 6.5) I use SKTsync to sync my device clock to one of the NIST or SNTP servers. It's freeware and it does it all for you, all you do is run the app. It's soooo simple. I also run an app called CT Scheduler lite. I use it to automatically run SKTsync every night.

Categories

Resources