2015年3月31日 星期二

[C#] How to get and set System Time?

According to the formal website of Microsoft MSDN, it depicts how to get and set System Time as shown below:
[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());
}
However, when we execute it, we will encounter the error message "Unable to load DLL 'coredll.dll': The specified module could not be found".

To fix it, just import "kernel32.dll" instead of "coredll.dll", as shown below:
[DllImport("kernel32.dll")]
private extern static void GetSystemTime(ref SYSTEMTIME lpSystemTime);

[DllImport("kernel32.dll")]
private extern static uint SetSystemTime(ref SYSTEMTIME lpSystemTime);

沒有留言:

張貼留言