2014-04-01 186 views
1

嗨,我知道这已被问过,但我需要帮助在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(); 
} 

但是,当我在我的系统上运行它,它显示了当前的日期/时间没有变化。我应该做出改变吗?
编辑:得到的消息失败:SetSystemTime失败,当我尝试运行

+0

这是例如测试目的?在这种情况下,抽象出时钟通常会更好(因此,除去直接调用'DateTime.Now')而不是摆弄系统的实际时间。 –

+0

此代码更改日期并将其还原。除非你将“FAILURE:SetSystemTime failed”设置为控制台 - 时间已成功更改..但是一些毫秒。删除“time-reverting part”,并根据需要调整代码。 – rufanov

+0

@Damien_The_Unbeliever实际上有一个应该生成用户指定的特定年份的数据的程序。认为只要用户想要特定年份的消息,就可以改变系统的日期时间 – Drake

回答

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()); 
} 

我没有测试它。但我希望它能起作用

+0

它是kernel32.dll导出的函数。它不存在于coredll.dll中。 TS示例中的代码完全正常并且正在工作。 – rufanov

+0

@rufanov它早先工作给我..这是从msdn文档http://msdn.microsoft.com/en-us/library/ms172517(v=vs.90).aspx –

+0

科雷尔一个是抛出一个异常寿......说不支持 – Drake