The new AddHandler statement makes it possible to attach event dynamically, that is without having to bind them via static code based on the Handles keyword. This keyword is also useful to have all the controls on a form share the same event procedure.
For example, say that you want to change the background of all textbox controls on the form when the focus enters in them, and restore the original color when the focus leaves them. Here’s the code code that does the trick:
Sub SetupEventHandlers() Dim ctrl As Control For Each ctrl In Me.Controls If TypeOf ctrl Is TextBox Then AddHandler ctrl.GotFocus, AddressOf Controls_GotFocus AddHandler ctrl.LostFocus, AddressOf Controls_LostFocus End If NextEnd SubPrivate Sub Controls_GotFocus(ByVal sender As Object, _ ByVal e As System.EventArgs) Dim ctrl As Control = CType(sender, Control) ' In a real application you should use system-defined colors. ctrl.BackColor = Color.YellowEnd SubPrivate Sub Controls_LostFocus(ByVal sender As Object, _ ByVal e As System.EventArgs) Dim ctrl As Control = CType(sender, Control) ' In a real application you should use system-defined colors. ctrl.BackColor = Color.WhiteEnd Sub