سؤال

كيف يمكنني تغيير النظام المحلي التاريخ والوقت برمجيا مع 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 ولكن الاحتجاج وظيفة في ويندوز دلل هو أفضل طريقة للقيام بذلك.

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 نظام التشغيل هذا سوف تتطلب وهو موجه UAC من أجل الحصول على ما يلزم من حقوق إدارية بنجاح تنفيذ SetSystemTime وظيفة.والسبب هو أن عملية الاستدعاء يحتاج SE_SYSTEMTIME_NAME امتياز.
  2. على SetSystemTime وظيفة يتوقع SYSTEMTIME البنية في التوقيت العالمي المنسق (UTC).وسوف لا تعمل على النحو المطلوب خلاف ذلك.

اعتمادا على أين/ كيف يمكنك الحصول على الخاص بك DateTime القيم, قد يكون من الأفضل أن يلعب هو آمن واستخدام ToUniversalTime() قبل وضع القيم المناظرة في SYSTEMTIME البنية.

مثال التعليمة البرمجية:

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 استدعاء Win32 API SetSystemTime,(على سبيل المثال)
  2. النظام.إدارة الطبقات مع فئة WMI Win32_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 صباحا");

ومنذ ذكرت ذلك في تعليق، وهنا 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 ، موافق.

ولكن يمكنني حذف DayOfWeek الممتلكات التي لم تستخدم ؛

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

يرجى توخي الحذر من أجل وجميع ميادين SystemTime هيكل.يوسف

<اقتباس فقرة>   

و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