[Journal - Late-bound Delegate Creation]

Late-bound Delegate Creation

Monday, May 31, 2004

Reflection, delegates, and events is a topic I can't seem to abandon. I've written about how to create and hook event handler delegates by means of reflection (recall that instantiating a delegate involves passing an actual function pointer), but I haven't incorporated that stuff fully into the Gregor.NET framework until now. While the Gregor.Core.Reflect module was able to create property delegates for some time, the more common case of creating method delegates was not supported directly.

The new CreateDelegate methods enable cool new techniques in WebEdit's built-in code interpreter. Suppose you have a generic event handling routine in an AddIn (see here for a discussion of how general event handlers can actually handle more specific types of events), and want to hook up one of WebEdit's events:

using Gregor.Core
sListenerType = "MyAddIn.Module1"
tpListener = Reflect.FindType(sListenerType, false)
sHandlerType = "Gregor.AppCore.Documents.DocumentEventHandler"
tpHandler = Reflect.FindType(sHandlerType, false)
del = Reflect.CreateDelegate(tpListener, "HandleIt", tpHandler)

That's the first part. Now we'll hook it up ("AddEventHandler" is just a convenience wrapper):

frm = WebEditApp.MainForm
Reflect.AddEventHandler(frm, "ActiveDocumentChanged", del)