TizzyT

MillisecondTimer -TizzyT

Oct 15th, 2015
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 2.37 KB | None | 0 0
  1. Imports System.Runtime.InteropServices
  2. Public Class MillisecondTimer
  3.     Public Event Elapsed()
  4.     Private mTimerId As Integer = 0
  5.     Private mHandler As TimerEventDel
  6.     Private _Interval As Integer = 0
  7.     Private Delegate Sub TimerEventDel(ByVal id As Integer, _
  8.                                        ByVal msg As Integer, _
  9.                                        ByVal user As IntPtr, _
  10.                                        ByVal dw1 As Integer, _
  11.                                        ByVal dw2 As Integer)
  12.     <DllImport("winmm.dll")> _
  13.     Private Shared Function timeBeginPeriod(ByVal msec As Integer) As Integer
  14.     End Function
  15.     <DllImport("winmm.dll")> _
  16.     Private Shared Function timeEndPeriod(ByVal msec As Integer) As Integer
  17.     End Function
  18.     <DllImport("winmm.dll")> _
  19.     Private Shared Function timeSetEvent(ByVal delay As Integer, ByVal resolution As Integer, _
  20.                                          ByVal handler As TimerEventDel, ByVal user As IntPtr, _
  21.                                          ByVal eventType As Integer) As Integer
  22.     End Function
  23.     <DllImport("winmm.dll")> _
  24.     Private Shared Function timeKillEvent(ByVal id As Integer) As Integer
  25.     End Function
  26.     Public Property Interval() As Integer
  27.         Get
  28.             Return _Interval
  29.         End Get
  30.         Set(value As Integer)
  31.             If mTimerId <> 0 Then [Stop]()
  32.             _Interval = value
  33.             Start()
  34.         End Set
  35.     End Property
  36.     Public Sub New()
  37.         timeBeginPeriod(1)
  38.         mHandler = New TimerEventDel(AddressOf TimerCallback)
  39.     End Sub
  40.     Public Sub New(ByVal Milliseconds As Integer)
  41.         timeBeginPeriod(1)
  42.         mHandler = New TimerEventDel(AddressOf TimerCallback)
  43.         _Interval = Milliseconds
  44.     End Sub
  45.     Public Sub Start()
  46.         If mTimerId = 0 Then mTimerId = timeSetEvent(_Interval, 0, mHandler, IntPtr.Zero, 1)
  47.     End Sub
  48.     Public Sub [Stop]()
  49.         timeKillEvent(mTimerId)
  50.         mTimerId = 0
  51.         timeEndPeriod(1)
  52.     End Sub
  53.     Private Sub TimerCallback(ByVal id As Integer, ByVal msg As Integer, _
  54.                               ByVal user As IntPtr, ByVal dw1 As Integer, ByVal dw2 As Integer)
  55.         If mTimerId <> 0 Then RaiseEvent Elapsed()
  56.     End Sub
  57.     Protected Overrides Sub Finalize()
  58.         timeKillEvent(mTimerId)
  59.         MyBase.Finalize()
  60.     End Sub
  61. End Class
Advertisement
Add Comment
Please, Sign In to add comment