Static and Dynamic Events : AddHandler « Event « VB.Net Tutorial






public class ValueEventArgs : Inherits EventArgs
   Private oldTemp As Decimal
   Private newTemp As Decimal

   Public ReadOnly Property OldValue As Decimal
      Get
         Return Me.oldTemp
      End Get   
   End Property

   Public ReadOnly Property NewValue As Decimal
      Get
         Return Me.newTemp
      End Get
   End Property

   Public Sub New(oldTemp As Decimal, newTemp As Decimal)
      Me.oldTemp = oldTemp
      Me.newTemp = newTemp   
   End Sub
End Class

Public Delegate Sub ValueEventHandler(sender As Object,ev As ValueEventArgs)

Public Class ValueMonitor
   Private currentValue As Decimal
   Private threshholdValue As Decimal

   Public Event ValueThreshold As ValueEventHandler 

   Public Sub New(threshHold As Decimal)
      Me.threshholdValue = threshHold
   End Sub

   Public Sub SetValue(newValue As Decimal)
      If (Me.currentValue > threshholdValue And _
         newValue <= Me.threshholdValue) Or _
         (Me.CurrentValue < Me.threshholdValue And _
             newValue >= Me.threshholdValue) Then
         OnRaiseValueEvent(newValue)
      End If
      Me.currentValue = newValue
   End Sub

   Public Function GetValue() As Decimal
      Return Me.currentValue
   End Function

   Protected Overridable Sub OnRaiseValueEvent(newValue As Decimal)
      RaiseEvent ValueThreshold(Me, New ValueEventArgs(Me.currentValue, _ 
                                       newValue))
   End Sub                                       
End Class

Public Module Example
   Public Sub Main()
      Dim tempMon As New ValueMonitor(32d)
      tempMon.SetValue(31)
      Console.WriteLine("Current temperature is {0} degrees Fahrenheit.",tempMon.GetValue())

      AddHandler tempMon.ValueThreshold, AddressOf TempMonitor

      tempMon.SetValue(33)
      Console.WriteLine("Current temperature is {0} degrees Fahrenheit.",tempMon.GetValue())

      RemoveHandler tempMon.ValueThreshold, AddressOf TempMonitor

      tempMon.SetValue(31)
      Console.WriteLine("Current temperature is {0} degrees Fahrenheit.",tempMon.GetValue())
   End Sub

   Private Sub TempMonitor(sender As Object, e As ValueEventArgs)
      Console.WriteLine("Value is changing from {0} to {1}.",e.OldValue, e.NewValue)
   End Sub 
End Module








11.2.AddHandler
11.2.1.Events Demonstration - AddHandlerEvents Demonstration - AddHandler
11.2.2.AddHandler btn.Click, AddressOf btn_ClickAddHandler btn.Click, AddressOf btn_Click
11.2.3.Add general to Label using AddHandler lblTitle.Click, AddressOf GenericEventAdd general to Label using AddHandler lblTitle.Click, AddressOf GenericEvent
11.2.4.Use AddHandler to add event handler to a buttonUse AddHandler to add event handler to a button
11.2.5.Static and Dynamic Events