2014-04-01 231 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