當任何程序或用戶修改系統時間的時候,系統會將 WM_TIMECHANGE
消息到所有的進程,我們的程序可以捕獲到該消息,然後將系統時間恢復到修改前的狀態,這樣就可以在我們的程序運行時系統時間的正確性,代碼如下:
'窗體form1(需要一個timer控件,interval=1000):
Private Sub Form_Load()
Timer1_Timer
RegisterWindow Me.hwnd '為窗口設置子類
End Sub
Private Sub Form_Unload(Cancel As Integer)
unRegisterWindow Me.hwnd '取消窗口的子類
End Sub
Private Sub Timer1_Timer()
OldTime = Now
End Sub
'模塊modle1:
Option Explicit
Public Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Public Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Public Declare Function CallWindowProc Lib "user32" Alias "CallWindowProcA" (ByVal lpPrevWndFunc As Long, ByVal hwnd As Long, ByVal msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Public Declare Function RegisterWindowMessage Lib "user32" Alias "RegisterWindowMessageA" (ByVal lpString As String) As Long
Public OldTime As String
Public ChangeFlag As Boolean
Public Const WM_TIMECHANGE As Long = &H1E '當系統的時間變化時發送此消息給所有頂級窗口
Public oldproc As Long
Private Type SYSTEMTIME
wYear As Integer
wMonth As Integer
wDayOfWeek As Integer
wDay As Integer
wHour As Integer
wMinute As Integer
wSecond As Integer
wMilliseconds As Integer
End Type
Private Declare Function SetLocalTime Lib "kernel32" (lpSystemTime As SYSTEMTIME) As Long
Public Function RegisterWindow(hwnd As Long) As Long
If hwnd <> 0 Then
oldproc = SetWindowLong(hwnd, -4, AddressOf WinProc)
End If
End Function
Public Function unRegisterWindow(hwnd As Long) As Long
If hwnd <> 0 Then
SetWindowLong hwnd, -4, oldproc
End If
End Function
Public Function WinProc(ByVal hwnd As Long, ByVal msg As Long, ByVal lpara As Long, ByVal wpara As Long) As Long
Dim i, mytt
If msg = WM_TIMECHANGE And ChangeFlag = False Then '系統時間被修改了而且不是本程序修改的
ChangeFlag = True '本程序要修改系統時間
Call SetToOldTime '修改系統時間
Exit Function
End If
ChangeFlag = False
WinProc = CallWindowProc(oldproc, hwnd, msg, lpara, wpara)
End Function
Public Function SetToOldTime() As String '將時間恢復到設置前的狀態
Dim tmp As String
tmp = OldTime '從保存的時間中取出修改前的系統時間
Dim lpSystemTime As SYSTEMTIME
lpSystemTime.wYear = Year(tmp) '取出年份
lpSystemTime.wMonth = Month(tmp) '取出月份
lpSystemTime.wDayOfWeek = -1
lpSystemTime.wDay = Day(tmp) '取出日
lpSystemTime.wHour = Hour(tmp) '取出小時
lpSystemTime.wMinute = Minute(tmp) '取出分鐘
lpSystemTime.wSecond = Second(tmp) '取出秒
lpSystemTime.wMilliseconds = 0
'set the new time
SetLocalTime lpSystemTime
End Function