I try to write some C# code to change time in my computer. This is the Main function of the console application I have. I compiled the code and get an exe file named TimeChange.exe
[StructLayoutAttribute(LayoutKind.Sequential)]
private struct SYSTEMTIME
{
public short year;
public short month;
public short dayOfWeek;
public short day;
public short hour;
public short minute;
public short second;
public short milliseconds;
}
[DllImport("kernel32.dll")]
static extern bool SetLocalTime(ref SYSTEMTIME time);
private static void Main(string[] args)
{
SYSTEMTIME st;
DateTime trts = DateTime.Now + new TimeSpan(0, 0, 10, 0);
st.year = (short)trts.Year;
st.month = (short)trts.Month;
st.dayOfWeek = (short)trts.DayOfWeek;
st.day = (short)trts.Day;
st.hour = (short)trts.Hour;
st.minute = (short)trts.Minute;
st.second = (short)trts.Second;
st.milliseconds = (short)trts.Millisecond;
Console.WriteLine("Setting time");
SetLocalTime(ref st);
Console.WriteLine("Setting finished");
Console.ReadLine();
}
However, I found that I need to be Administrator before I can change the time. I am sure if I right click the compiled exe file and select Run as Administrator, the time can be changed. After doing some search, I found that CPAU can help to run an application as an Administrator. Then I downloaded CPAU and put the CPAU in the same folder as the TimeChange.exe. In Windows command line (not in Administrator mode), I ran
CPAU -u Username -p Password -ex "TimeChange.exe" -wait -LWP
In the command line, it shown that
CPAU V01.11.00cpp Joe Richards (joe@joeware.net) November 2005
Current Security Context: Group-PC\Username
Process Created...
The command completed successfully.
However, the time was not changed.
Can anyone help to see what is the possible problem? Thank you.