Adding an event handler using reflection?

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)
 
B

Bruce Wood

Have you tried,

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

?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top