Adding an event handler using reflection?

  • Thread starter Thread starter John Dumais
  • Start date Start date
J

John Dumais

Hello,

I'm trying to create an application that can allow users to extend the
menu by supplying the event handlers in their own libraries. My first
thought was to use reflection to specify the event handler, something
like this...

// The user's assembly has already been loaded and we have created an
// instance of the type the user specifies

MenuItem menuItem = new MenuItem("TextTheUserTellsMe");

// Here's where the problem is... I'm trying connect the Clieck event
// delegate to the handler by doing this...
menuItem.Click += (System.EventHandler)Delegate.CreateDelegate(type,
typeInstance, instanceMethodName);

This last line results in an exception like this...

An unhandled exception of type 'System.ArgumentException' occurred in
mscorlib.dll

Additional information: Type must derive from Delegate.

I think I don't understand something fundamental. Any suggestions
getting me pointed in the right direction would be appreciated.

(e-mail address removed)
 
Have you tried,

menuItem.Click +=
(System.EventHandler)Delegate.CreateDelega­te(typeof(System.EventHandler),
typeInstance, instanceMethodName);

?
 
Back
Top