Delegates are one of the latest additions to the VB.NET language. Delegates are classes that inherit from either System.Delegate or System.MulticastDelegate. In VB.NET, delegates by default inherit from System.MulticastDelegate. A delegate is a class that acts as a wrapper around a function pointer. This allows function pointers, or delegates, to be object-oriented, typesafe, and secure.

A delegate can point to both a shared function and one that is associated with an instance of a class. A delegate that inherits from the System.Delegate class can only point to a single function at any one time. The delegate that inherits from the System.MulticastDelegate class, however, can point to a list of functions, all of which are called in succession when this type of delegate is used. The thing to watch out for when using multicast delegates is that, if the functions the delegate points to have a return value, the delegate’s final return value is the return value of the last function the delegate calls. For this reason, you should use delegates that point to a single function when implementing hooks.

A Simple Example Using Delegates

To better understand delegates, let’s examine a simple example that shows how to set up and use both the delegate and multicast delegate. Figure 23-1 presents a screenshot of this example application. Table 23-1 presents the nondefault properties of the form and its controls.

Figure 23-1. Screenshot of the delegate example application

Table 23-1. Nondefault ...

Get Subclassing and Hooking with Visual Basic now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.