문제

C#으로 프로그래밍 방식으로 로컬 시스템의 날짜 및 시간을 어떻게 변경하려면?

도움이 되었습니까?

해결책

여기에 내가 답을 찾은 곳이 있습니다.

명확성을 향상시키기 위해 여기에 다시 게시했습니다.

이 구조 정의 :

[StructLayout(LayoutKind.Sequential)]
public struct SYSTEMTIME
{
    public short wYear;
    public short wMonth;
    public short wDayOfWeek;
    public short wDay;
    public short wHour;
    public short wMinute;
    public short wSecond;
    public short wMilliseconds;
}

다음을 추가하십시오 extern 수업에 대한 방법 :

[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool SetSystemTime(ref SYSTEMTIME st);

그런 다음 다음과 같은 구조물 인스턴스로 메소드를 호출하십시오.

SYSTEMTIME st = new SYSTEMTIME();
st.wYear = 2009; // must be short
st.wMonth = 1;
st.wDay = 1;
st.wHour = 0;
st.wMinute = 0;
st.wSecond = 0;

SetSystemTime(ref st); // invoke this method.

다른 팁

DOS 명령에 호출을 사용할 수 있지만 Windows DLL의 함수를 호출하는 것이 더 나은 방법입니다.

public struct SystemTime
{
    public ushort Year;
    public ushort Month;
    public ushort DayOfWeek;
    public ushort Day;
    public ushort Hour;
    public ushort Minute;
    public ushort Second;
    public ushort Millisecond;
};

[DllImport("kernel32.dll", EntryPoint = "GetSystemTime", SetLastError = true)]
public extern static void Win32GetSystemTime(ref SystemTime sysTime);

[DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
public extern static bool Win32SetSystemTime(ref SystemTime sysTime);

private void button1_Click(object sender, EventArgs e)
{
    // Set system date and time
    SystemTime updatedTime = new SystemTime();
    updatedTime.Year = (ushort)2009;
    updatedTime.Month = (ushort)3;
    updatedTime.Day = (ushort)16;
    updatedTime.Hour = (ushort)10;
    updatedTime.Minute = (ushort)0;
    updatedTime.Second = (ushort)0;
    // Call the unmanaged function that sets the new date and time instantly
    Win32SetSystemTime(ref updatedTime);
}  

많은 훌륭한 관점과 접근 방식이 이미 여기에 있지만, 여기에 현재 제외되어 일부 사람들을 혼란스럽게 할 수있는 몇 가지 사양이 있습니다.

  1. Windows Vista, 7, 8 OS 이것은 할 것입니다 필요하다 성공적으로 실행하는 데 필요한 관리 권한을 얻기 위해 UAC 프롬프트 SetSystemTime 기능. 그 이유는 호출 프로세스가 필요하기 때문입니다 se_systemtime_name 특권.
  2. 그만큼 SetSystemTime 함수는 기대하고 있습니다 SYSTEMTIME 조정 된 보편적 시간에 구조 (UTC). 그렇지 않으면 원하는대로 작동하지 않습니다.

어디서/ 어떻게 얻는 지에 따라 DateTime 가치, 안전하고 사용하는 것이 가장 좋습니다. ToUniversalTime() 해당 값을 설정하기 전에 SYSTEMTIME 구조.

Code example:

DateTime tempDateTime = GetDateTimeFromSomeService();
DateTime dateTime = tempDateTime.ToUniversalTime();

SYSTEMTIME st = new SYSTEMTIME();
// All of these must be short
st.wYear = (short)dateTime.Year;
st.wMonth = (short)dateTime.Month;
st.wDay = (short)dateTime.Day;
st.wHour = (short)dateTime.Hour;
st.wMinute = (short)dateTime.Minute;
st.wSecond = (short)dateTime.Second;

// invoke the SetSystemTime method now
SetSystemTime(ref st); 
  1. Pinvoke To Call Win32 API SetSystemTime (예시)
  2. WMI 클래스 WAN32_OPERATINGSYSTEM을 통한 관리 클래스 및 해당 클래스에서 SETDATETIME을 호출합니다.

둘 다 발신자에게 sesystemtimeprivilege가 부여 되었으며이 권한이 활성화되어야합니다.

이 기능을 사용하여 시스템 시간을 변경하십시오 (창 8에서 테스트)

 void setDate(string dateInYourSystemFormat)
    {
        var proc = new System.Diagnostics.ProcessStartInfo();
        proc.UseShellExecute = true;
        proc.WorkingDirectory = @"C:\Windows\System32";
        proc.CreateNoWindow = true;
        proc.FileName = @"C:\Windows\System32\cmd.exe";
        proc.Verb = "runas";
        proc.Arguments = "/C date " + dateInYourSystemFormat;
        try
        {
            System.Diagnostics.Process.Start(proc);
        }
        catch
        {
            MessageBox.Show("Error to change time of your system");
            Application.ExitThread();
        }
    }
void setTime(string timeInYourSystemFormat)
    {
        var proc = new System.Diagnostics.ProcessStartInfo();
        proc.UseShellExecute = true;
        proc.WorkingDirectory = @"C:\Windows\System32";
        proc.CreateNoWindow = true;
        proc.FileName = @"C:\Windows\System32\cmd.exe";
        proc.Verb = "runas";
        proc.Arguments = "/C time " + timeInYourSystemFormat;
        try
        {
            System.Diagnostics.Process.Start(proc);
        }
        catch
        {
            MessageBox.Show("Error to change time of your system");
            Application.ExitThread();
        }
    }

예시: 양식의로드 방법으로 호출하십시오setDate ( "5-6-92"); settime ( "2 : 4 : 5 am");

의견으로 언급 한 이후 C ++/CLI 래퍼는 다음과 같습니다.

#include <windows.h>
namespace JDanielSmith
{
    public ref class Utilities abstract sealed /* abstract sealed = static */
    {
    public:
        CA_SUPPRESS_MESSAGE("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")
        static void SetSystemTime(System::DateTime dateTime) {
            LARGE_INTEGER largeInteger;
            largeInteger.QuadPart = dateTime.ToFileTimeUtc(); // "If your compiler has built-in support for 64-bit integers, use the QuadPart member to store the 64-bit integer."


            FILETIME fileTime; // "...copy the LowPart and HighPart members [of LARGE_INTEGER] into the FILETIME structure."
            fileTime.dwHighDateTime = largeInteger.HighPart;
            fileTime.dwLowDateTime = largeInteger.LowPart;


            SYSTEMTIME systemTime;
            if (FileTimeToSystemTime(&fileTime, &systemTime))
            {
                if (::SetSystemTime(&systemTime))
                    return;
            }


            HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
            throw System::Runtime::InteropServices::Marshal::GetExceptionForHR(hr);
        }
    };
}

C# 클라이언트 코드는 이제 매우 간단합니다.

JDanielSmith.Utilities.SetSystemTime(DateTime.Now);

조심해요!. 구조에서 사용하지 않은 속성을 삭제하면 시간이 잘못되었습니다. 나는 이것 때문에 1 일을 잃었다. 구조의 순서가 중요하다고 생각합니다.

이것은 올바른 구조입니다.

public struct SystemTime
        {
            public ushort Year;
            public ushort Month;
            public ushort DayOfWeek;
            public ushort Day;
            public ushort Hour;
            public ushort Minute;
            public ushort Second;
            public ushort Millisecond;

        };

setsystemtime ()을 실행하면 예상대로 작동합니다. 테스트를 위해 아래와 같이 시간을 설정했습니다.

SystemTime st = new SystemTime();
st.Year = 2019;
st.Month = 10;
st.Day = 15;
st.Hour = 10;
st.Minute = 20;
st.Second = 30;

SetSystemTime(ref st);

시간 세트 : 15.10.2019 10:20, OK.

그러나 나는 사용되지 않은 주간의 재산을 삭제합니다.

public struct SystemTime
            {
                public ushort Year;
                public ushort Month;
                public ushort Day;
                public ushort Hour;
                public ushort Minute;
                public ushort Second;
                public ushort Millisecond;

            };

SystemTime st = new SystemTime();
    st.Year = 2019;
    st.Month = 10;
    st.Day = 15;
    st.Hour = 10;
    st.Minute = 20;
    st.Second = 30;

    SetSystemTime(ref st);

동일한 코드를 실행하지만 시간은 10.10.2019 20:30으로 설정합니다.

순서와 시스템 시간 구조의 모든 필드를주의하십시오. 유수프

proc.arguments = "/c 날짜 :" + dateinyoursystemformat;

이것은 작업 기능입니다.

void setDate(string dateInYourSystemFormat)
{
    var proc = new System.Diagnostics.ProcessStartInfo();
    proc.UseShellExecute = true;
    proc.WorkingDirectory = @"C:\Windows\System32";
    proc.CreateNoWindow = true;
    proc.FileName = @"C:\Windows\System32\cmd.exe";
    proc.Verb = "runas";
    proc.Arguments = "/C Date:" + dateInYourSystemFormat;
    try
    {
        System.Diagnostics.Process.Start(proc);
    }
    catch
    {
        MessageBox.Show("Error to change time of your system");
        Application.ExitThread();
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top