Question

Comment puis-je modifier la date & amp; du système local? temps programmatique avec C #?

Était-ce utile?

La solution

Voici où j'ai trouvé la réponse.

Je l'ai republié ici pour améliorer la clarté.

Définissez cette structure:

[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;
}

Ajoutez la méthode extern suivante à votre classe:

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

Appelez ensuite la méthode avec une instance de votre structure comme suit:

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.

Autres conseils

Vous pouvez utiliser un appel à une commande DOS, mais l'appel de la fonction dans la DLL Windows est un meilleur moyen de le faire.

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);
}  

Il existe déjà beaucoup de points de vue et d’approches intéressants, mais voici quelques spécifications qui sont actuellement laissées de côté et qui, à mon avis, pourraient faire trébucher et dérouter certaines personnes.

  1. Sous Windows Vista, 7, 8 systèmes d’exploitation , il vous faudra une invite UAC afin d’obtenir les droits administratifs nécessaires pour exécuter avec succès SetSystemTime fonction. La raison en est que le processus d’appel a besoin du privilège SE_SYSTEMTIME_NAME .
  2. La fonction SetSystemTime attend une structure SYSTEMTIME dans le temps universel coordonné (UTC) . Cela ne fonctionnera pas comme souhaité autrement.

Selon l'endroit où et comment vous obtenez vos valeurs DateTime , il peut être préférable de jouer prudemment et d'utiliser ToUniversalTime () avant de définir les valeurs correspondantes dans SYSTEMTIME struct.

Exemple de code:

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 doit appeler l’API Win32 SetSystemTime, ( exemple . )
  2. Classes System.Management avec la classe WMI Win32_OperatingSystem et appelez SetDateTime sur cette classe.

Les deux requièrent que l'appelant ait reçu SeSystemTimePrivilege et que ce privilège soit activé.

Utilisez cette fonction pour modifier l'heure du système (testé dans la fenêtre 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();
        }
    }

Exemple: Appeler la méthode de chargement du formulaire setDate ("5-6-92"); setTime ("2: 4: 5 AM");

Puisque je l'ai mentionné dans un commentaire, voici un wrapper 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);
        }
    };
}

Le code du client C # est maintenant très simple:

JDanielSmith.Utilities.SetSystemTime(DateTime.Now);

Soyez prudent! Si vous supprimez une propriété inutilisée de la structure, l'heure sera incorrecte. J'ai perdu 1 jour à cause de cela. Je pense que l'ordre de la structure est important.

C'est la structure correcte:

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;

        };

Si vous exécutez SetSystemTime (), cela fonctionne comme prévu. Pour le test, je règle l'heure comme ci-dessous;

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);

L'heure définie: 15.10.2019 10h20, c'est bien.

Mais je supprime la propriété DayOfWeek qui n’a pas été utilisée;

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);

Exécuter le même code, mais l'heure a été définie sur: 10.10.2019 20:30

Faites attention à l'ordre et à tous les champs de la structure SystemTime. Yusuf

  

proc.Arguments = " / C Date: " + dateInYourSystemFormat;

Ceci est une fonction:

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();
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top