プログラムでシステムの日付を変更する
質問
ローカルシステムの日付を変更するにはどうすればよいですか<!> amp; 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);
}
多くの優れた視点とアプローチがすでにここにありますが、現在残されているいくつかの仕様があります。これは、つまずき、一部の人々を混乱させるかもしれません。
- Windows Vista、7、8 OS では、
SetSystemTime
関数を正常に実行するために必要な管理者権限を取得するために、UACプロンプトが必要になります。その理由は、呼び出しプロセスには SE_SYSTEMTIME_NAME 特権が必要だからです。 -
SYSTEMTIME
関数は、協定世界時(UTC)にDateTime
構造体が必要です。それ以外の場合は、期待どおりに機能しません。
ToUniversalTime()
値を取得する場所/方法によっては、安全にプレイして <=> で、<=>構造体に対応する値を設定します。
コード例:
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);
- Win32 API SetSystemTimeを呼び出すPInvoke、( 例 )
- WMIクラスがWin32_OperatingSystemのSystem.Managementクラスで、そのクラスで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(<!> quot; 5-6-92 <!> quot;); setTime(<!> quot; 2:4:5 AM <!> quot;);
コメントで説明したので、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 = <!> quot; / C Date:<!> quot; + 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();
}
}