簡體   English   中英

更改系統日期,時間

[英]Change system date,time

嗨,我知道這已經被問過了,但是我需要在c#中更改系統日期時間的幫助。 在進行Google搜索時,我發現了一個建議以下代碼的網站

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失敗

您應該使用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());
}

我還沒有測試。 但我希望它能起作用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM