devxlogo

Adding events dynamically in a Windows Form

Adding events dynamically in a Windows Form

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

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist