更改系统日期,时间

时间:2014-04-01 07:23:31

标签: c# date time

您好我之前已经问过这个问题,但我需要帮助改变c#中的系统日期时间。在进行谷歌搜索时,我发现了一个建议以下代码的网站

public struct SYSTEMTIME 
{    
    public ushort wYear,wMonth,wDayOfWeek,wDay, wHour,wMinute,wSecond,wMilliseconds;
}

[DllImport("kernel32.dll")]
public extern static void GetSystemTime(ref SYSTEMTIME lpSystemTime);

/// <param name="lpSystemTime">[in] Pointer to a SYSTEMTIME structure that
/// contains the current system date and time.</param>
[DllImport("kernel32.dll")]
public extern static uint SetSystemTime(ref SYSTEMTIME lpSystemTime);

static void Main()
{    
    Console.WriteLine(DateTime.Now.ToString());
    SYSTEMTIME st = new SYSTEMTIME();
    GetSystemTime(ref st);
    Console.WriteLine("Adding 1 hour...");
    st.wHour = (ushort)(st.wHour + 1 % 24);
    if (SetSystemTime(ref st) == 0)
        Console.WriteLine("FAILURE: SetSystemTime failed");
    Console.WriteLine(DateTime.Now.ToString());
    Console.WriteLine("Setting time back...");
    st.wHour = (ushort)(st.wHour - 1 % 24);
    SetSystemTime(ref st);
    Console.WriteLine(DateTime.Now.ToString());
    Console.WriteLine("Press Enter to exit");
    Console.Read();
}

但是当我在我的系统中运行它时,它显示当前日期/时间没有变化。我应该做出任何改变吗? 编辑:当我尝试运行

时收到消息FAILURE:SetSystemTime失败

1 个答案:

答案 0 :(得分:1)

你应该使用coredll.dll来存档这个..

[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; 
}

private void GetTime()
{
    // Call the native GetSystemTime method 
    // with the defined structure.
    SYSTEMTIME stime = new SYSTEMTIME();
    GetSystemTime(ref stime);

    // Show the current time.           
    MessageBox.Show("Current Time: "  + 
        stime.wHour.ToString() + ":"
        + stime.wMinute.ToString());
}
private void SetTime()
{
    // Call the native GetSystemTime method 
    // with the defined structure.
    SYSTEMTIME systime = new SYSTEMTIME();
    GetSystemTime(ref systime);

    // Set the system clock ahead one hour.
    systime.wHour = (ushort)(systime.wHour + 1 % 24);
    SetSystemTime(ref systime);
    MessageBox.Show("New time: " + systime.wHour.ToString() + ":"
        + systime.wMinute.ToString());
}

我还没有测试过。但我希望它会起作用