The problem here is that the EventHandler constructor is a special method
and cannot be invoked via reflection. To overcome this we create a helper
class:
public class Invoker
{
private MethodInfo m_mi;
object m_target;
public Invoker(object target, string method)
{
m_target = target;
m_mi = target.GetType().GetMethod(method,
BindingFlags.NonPublic|BindingFlags.Public|BindingFlags.Instance);
if ( m_mi == null )
throw new ArgumentOutOfRangeException("Method not found");
}
public void Invoke(object sender, EventArgs e)
{
if ( m_mi != null )
m_mi.Invoke(m_target, new object[] { sender, e });
}
}
Then, given the target control and the event handler ( we have the form
myForm and the event handler method name event_name ) we do the following:
// Get the descriptor of the event (by name).
EventInfo ei = myPictureBox.GetType().GetEvent("Click");
// Create an instance of Invoker that targets the event handler
Invoker invoker = new Invoker(myForm, event_name);
// Add the event handler exposed by Invoker
ei.AddEventHandler(myPictureBox, new EventHandler(invoker.Invoke));
--
Alex Feinman
---
Visit
http://www.opennetcf.org
"lagay" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed)...
>I have a class library that is called from a form that adds controls to the
> form at runtime. I am currently working on creating a PictureBox control
> at
> runtime and am having problems trying to hook up code to the click event
> of
> the PictureBox. The form will contain the code for the click event and I
> need to add this event to the PictureBox control at runtime from the class
> library.
>
> myPictureBox.Click += new EventHandler(event_name);
>
> I know I need to use Reflection; but there are many methods that have been
> removed from the compactframework that I just can't figure out how to
> accomplish what I need to do. Has anyone done this before?
>
> Thanks,
>
> Lisa
>
>
>
>
>
>
>