How to determine if an event is already subscribed

前端 未结 7 1727
傲寒
傲寒 2020-11-29 02:08

In my .NET application I am subscribing to events from another class. The subscription is conditional. I am subscribing to events when the control is visible and de-subscrib

7条回答
  •  日久生厌
    2020-11-29 02:58

      /// 
      /// Determine if a control has the event visible subscribed to
      /// 
      /// The control to look for the VisibleChanged event
      /// True if the control is subscribed to a VisibleChanged event, False otherwise
      private bool IsSubscribed(Control controlObject)
      {
         FieldInfo event_visible_field_info = typeof(Control).GetField("EventVisible",
            BindingFlags.Static | BindingFlags.NonPublic);
         object object_value = event_visible_field_info.GetValue(controlObject);
         PropertyInfo events_property_info = controlObject.GetType().GetProperty("Events",
            BindingFlags.NonPublic | BindingFlags.Instance);
         EventHandlerList event_list = (EventHandlerList)events_property_info.GetValue(controlObject, null);
         return (event_list[object_value] != null);
      }
    

提交回复
热议问题