Public Class Form1
< DllImport("kernel32.dll", SetLastError:=True) >
Private Shared Function SetSystemTime(ByRef systime As SYSTEMTIME) As Boolean
End Function
< StructLayout(LayoutKind.Sequential) >
Public Structure SYSTEMTIME
Public year As Short
Public month As Short
Public dayOfWeek As Short
Public day As Short
Public hour As Short
Public minute As Short
Public second As Short
Public milliseconds As Short
End Structure
' 更改系统时间的函数
Public Sub ChangeSystemTime(newDateTime As DateTime)
Dim sysTime As New SYSTEMTIME()
sysTime.year = CType(newDateTime.Year, Short)
sysTime.month = CType(newDateTime.Month, Short)
sysTime.day = CType(newDateTime.Day, Short)
sysTime.hour = CType(newDateTime.Hour, Short)
sysTime.minute = CType(newDateTime.Minute, Short)
sysTime.second = CType(newDateTime.Second, Short)
sysTime.milliseconds = CType(newDateTime.Millisecond, Short)
If SetSystemTime(sysTime) Then
' 成功更改时间
MessageBox.Show("系统时间已更改。")
Else
' 更改失败,可以通过Marshal.GetLastWin32Error()获取错误代码
MessageBox.Show("更改系统时间失败,错误代码:" & Marshal.GetLastWin32Error().ToString())
End If
End Sub
End Class
调用
Dim a As New Form1()
a.ChangeSystemTime(New Date(2024, 12, 9, 12, 0, 0))