By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,908 Members | 2,056 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,908 IT Pros & Developers. It's quick & easy.

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

P: n/a
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;
EventData.Add(ed);
ed.Unwire(myComponent);
}
//Do something with button1 here . . .

// now rewire . . .

foreach(EventDatum ed in EventData)
if (ed != null)
ed.Wire(myComponent);
EventData.Clear();
=============================
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
{
get
{
return
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance| BindingFlags.IgnoreCase|
BindingFlags.Static;
}
}

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
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.