How can I change the System Time?

  • Thread starter Thread starter revna
  • Start date Start date
R

revna

I want to change my System clock with an c# programm, but
dateTime are readonly, or?

thanx for help
 
revna, you will have to use p/invoke to do this. Here's the code you'll
need. First the struct:

[StructLayout(Layout.Sequential)]
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;
}

And second, here's the function you need to use.

[DllImport("kernel32.dll")]
static extern bool SetSystemTime(ref SYSTEMTIME time);
 
Hi,
The .NET framework doesn't have managed interfaces for all of Win32 API, so
you have to write special code to use things that are built into Windows.
Platform Invoke (P/Invoke) is the most common way to do this. To use
P/Invoke, you write a prototype that describes how the function should be
called, and then the runtime uses this information to make the call. The
other way to do this is by wrapping the functions using the Managed
Extensions to C++.

Here is what you can do to change the system time: (Look at this article
"Using Win32 and Other Libraries" by Eric Gunnerson on MSDN for more info.)

using System;
using System.Runtime.InteropServices;

public struct SystemTime {
public short wYear;
public short wMonth;
public short wDayOfWeek;
public short wDay;
public short wHour;
public short wMinute;
public short wSecond;
public short wMilliseconds;
}


public class MyTimeAdjuster
{
[DllImport("kernel32.dll")]
public static extern bool GetSystemTime(ref SystemTime systemTime);
[DllImport("kernel32.dll")]
public static extern bool SetSystemTime(ref SystemTime systemTime);

void SetNewTime(short hour, short minutes)
{
SystemTime st = new SystemTime();
GetSystemTime(ref st);
st.wHour = hour;
st.wMinute = minutes;
SetSystemTime(ref st);
}

public static void Main(string[] args)
{
MyTimeAdjuster myTime = new MyTimeAdjuster();
myTime.SetNewTime( 12, 50);
}
}

Hope this helps,
Martha
 
Back
Top