0

Based on this question I am trying to do the same thing for the TextBox Leave event. This should have been a no-brainer and I created an extension method as follows:

public static class TextBoxExtensions
{
    public static bool IsLeaveEventWired(this TextBox txt)
    {
        var eventKey = typeof(TextBox).GetField("EVENT_LEAVE",
                               System.Reflection.BindingFlags.NonPublic |
                               System.Reflection.BindingFlags.Static)
                              .GetValue(txt);

        EventHandlerList eventList = typeof(TextBox).GetProperty("Events",
                             System.Reflection.BindingFlags.NonPublic |
                             System.Reflection.BindingFlags.Instance)
                            .GetValue(txt, null) as EventHandlerList;

        return eventList[eventKey] != null;
    }
}

The problem is that apparently the EVENT_LEAVE key does not exist because I am getting a NullReferenceException. So far I have tried getting all the TextBox's fields but I only get one FieldInfo object "EVENT_TEXTALIGNCHANGED" which is not an event that I have a handler for and the two events that I do, "Leave" and "KeyUp" are not included in the list.

So as the title of the question, how can I find the key to the TextBox's Leave event to see if it is wired or not?

Thank you.

Sergio Romero
  • 6,477
  • 11
  • 41
  • 71
  • @RufusL - It did not work. I have tried this exact same code from the original post with a ComboBox and it does work as is. the issue here is to figure out the Leave event key. I suppose. – Sergio Romero Nov 08 '18 at 21:53
  • Well when I do `typeof(TextBox).GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)`, it returns only a single item, named `EVENT_TEXTALIGNCHANGED`, so it seems like something else is needed. – Rufus L Nov 08 '18 at 22:12
  • [How to check which event are assigned?](https://stackoverflow.com/questions/15630943/how-to-check-which-event-are-assigned?answertab=active#tab-top). [Determine list of event handlers bound to event](https://stackoverflow.com/questions/660480/determine-list-of-event-handlers-bound-to-event?answertab=active#tab-top). – Jimi Nov 09 '18 at 01:50
  • But, if you're looking for a way to keep track of what event are assigned to a Control/Class or verify whether a Component has already an event handler attached to an event, you could consider a class that is delegated to this task from the beginning. See the examples on: [How to: Handle Multiple Events Using Event Properties](https://learn.microsoft.com/en-us/dotnet/standard/events/how-to-handle-multiple-events-using-event-properties) and the [EventHandlerList](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.eventhandlerlist) Class. – Jimi Nov 09 '18 at 01:51

0 Answers0