最近寫個東西用到延時函數,整理一下:
代碼1Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)代碼2Private Declare Function timeGetTime Lib "winmm.dll" () As LongFunction Delaytime(Milliseconds As Integer) Dim Savetime As Double Savetime = timeGetTime '記下開始時的時間 While timeGetTime < Savetime + Milliseconds '迴圈等待 DoEvents '轉讓控制權,以便讓作業系統處理其它的事件。 WendEnd Function代碼3Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)Private Declare Function timeGetTime Lib "winmm.dll" () As LongFunction Delaytime(Milliseconds As Integer) '改造後的延時程式 Dim Savetime As Double Savetime = timeGetTime '記下開始時的時間 While timeGetTime < Savetime + Milliseconds '迴圈等待 Sleep (30) '加上這麼一句後,該函數延時不佔用CPU資源,也不像sleep函數,調用後程式無反應了。 DoEvents '轉讓控制權,以便讓作業系統處理其它的事件。 WendEnd Function以上三個代碼都能延時,代碼一的缺點是延時間長度點後,在延時過程中程式無反應了;代碼二的缺點是延時的時候程式有反應,延時過程中CPU接近100%,代碼三是結合前兩個代碼,延時過程中程式也有反應,CPU佔用也小。