471,337 Members | 1,338 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,337 software developers and data experts.

PROBLEM SOLVED-(HOWTO)Dynamically Disable/Enable Component events!

I know it works for basic widows form components. . .
Similar approach can be applied for other controls if this doesn't work . . .

Typical Usage:
ArrayList eventData = new ArrayList();
EventDescriptorCollection events = TypeDescriptor.GetEvents(myComponent);
foreach (System.ComponentModel.EventDescriptor myEvent in events)
//Unwire the events
EventDatum ed = EventDatum.Create(button1, myEvent);
if (ed == null) continue;
//Do something with button1 here . . .

// now rewire . . .

foreach(EventDatum ed in EventData)
if (ed != null)
EventDatum listing (assumes project appropriate references)
public class EventDatum
private EventDescriptor _eventDesc;
private Delegate _event;
private static MethodInfo GetEventsMethod(Type objType)
MethodInfo mi = objType.GetMethod("get_Events",All);
if ((mi ==null)& (objType.BaseType!=null))
mi = GetEventsMethod(objType.BaseType);
return mi;

private static EventHandlerList GetEvents(object obj)
MethodInfo mi = GetEventsMethod(obj.GetType());
if (mi == null) return null;
return (EventHandlerList) mi.Invoke(obj, new object[]{});

private static FieldInfo GetEventIDField(Type objType, string eventName)
FieldInfo fi = objType.GetField("Event"+eventName,All);
if ((fi ==null)& (objType.BaseType!=null))
fi = GetEventIDField(objType.BaseType, eventName);
return fi;

private static object GetEventID(object obj, string eventName)
FieldInfo fi = GetEventIDField(obj.GetType(), eventName);
if (fi ==null) return null;
return fi.GetValue(obj);

private static BindingFlags All
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance| BindingFlags.IgnoreCase|

internal EventDatum(EventDescriptor desc, Delegate aEvent)
_eventDesc = desc;
_event = aEvent;

public static EventDatum Create(object obj, EventDescriptor desc)
EventHandlerList list = GetEvents(obj);
if (list==null) return null;
object key = GetEventID(obj, desc.Name);
if (key==null) return null;
Delegate evnt = list[key];
if (evnt == null) return null;
return new EventDatum(desc, evnt);

public void Wire(object obj)
_eventDesc.AddEventHandler(obj, _event);

public void Unwire(object obj)
_eventDesc.RemoveEventHandler(obj, _event);
Jul 21 '05 #1
0 922

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by Eric | last post: by
1 post views Thread by José Joye | last post: by
2 posts views Thread by ezmiller | last post: by
11 posts views Thread by onkar.n.mahajan | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.