here it is, C# code snippet that uses unmanaged code to retrieve the current date and time of the Windows operating system, and also sets it to the specified values.
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Windows.Forms;
- using System.Runtime.InteropServices;
- namespace Sample
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- 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
- updatedTime.Year = (ushort)2008;
- updatedTime.Month = (ushort)4;
- updatedTime.Day = (ushort)23;
- // UTC time; it will be modified according to the regional settings of the target computer so the actual hour might differ
- 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);
- // Retrieve the current system date and time
- Win32GetSystemTime(ref currTime);
- // You can now use the struct to retrieve the date and time
- MessageBox.Show("It's " + currTime.Hour + " o'clock. Do you know where your C# code is?");
- }
- }
- }
No comments:
Post a Comment