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

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS