Windows Forms: How to change system date in C#
By FoxLearn 9/14/2020 5:34:58 AM 7.65K
This post shows you How to change system date in C#.
Dragging DateTimePicker, Button from the Visual Studio toolbox into your form designer, then design a simple UI allows you to change the system date as shown below.
Defining a struct datetime as shown below.
public struct SystemDate { public ushort Year; public ushort Month; public ushort DayOfWeek; public ushort Day; public ushort Hour; public ushort Minute; public ushort Second; public ushort Millisecond; };
How to change system date and time using c#
Next, We will use Win32 API to set the system date time.
[DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)] public extern static bool SetSystemTime(ref SystemDate sysDate);
Adding a click event handler to the Save button allows you to change the system date.
//c# set system time windows 10 private void btnSave_Click(object sender, EventArgs e) { SystemDate systemDate = new SystemDate(); systemDate.Month = (ushort)dateTimePicker.Value.Month; systemDate.Day = (ushort)dateTimePicker.Value.Day; systemDate.Year = (ushort)dateTimePicker.Value.Year; var result = SetSystemTime(ref systemDate); if (result) MessageBox.Show("You have successfully changed the system date.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); }
If you want to change system date time in c#, you can modify your code as shown below.
DateTime date = new DateTime(2020, 13, 9, 11, 30, 15, 0, DateTimeKind.Utc); SystemDate systime = new SystemDate(date); SetSystemTime(ref systime);
and don't forget to add a constructor to your SystemDate struct.
public SystemDate(DateTime dt) { Year = (ushort)dt.Year; Month = (ushort)dt.Month; DayOfWeek = (ushort)dt.DayOfWeek; Day = (ushort)dt.Day; Hour = (ushort)dt.Hour; Minute = (ushort)dt.Minute; Second = (ushort)dt.Second; Milliseconds = (ushort)dt.Millisecond; }
Through this post you can easily set system date time in windows using c#.
Categories
Popular Posts
Visual Studio: Auto increment version
04/01/2024
What is ARM architecture?
04/01/2024