I need to create a RichTextBox subclass that works the same in all ways except that it does not subscribe to UserPreferenceChanged. This event is causing a hang in my app. I have to use a RichTextBox and can't swap it for a TextBox with MultiLine=True, or anything else like that.
This is where System.Windows.Forms.RichTextBox subscribes;
protected override void OnHandleCreated(EventArgs e)
{
...
SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(this.UserPreferenceChangedHandler);
}
This is the signature of the handler;
private void UserPreferenceChangedHandler(object o, UserPreferenceChangedEventArgs e)
The handler is not virtual so I can't override it. The handler is private so I can't do a simple -= to unsubscribe. I've looked into using reflection to remove the handler but I can't get it to work - this is what i have so far;
public partial class MyRichTextBox : RichTextBox
{
...
private void UnsubscribeUserPreferenceChanged()
{
FieldInfo fieldInfo = typeof(SystemEvents).GetField("OnUserPreferenceChangedEvent", BindingFlags.NonPublic | BindingFlags.Static);
// fieldInfo.ToString() = "System.Object.OnUserPreferenceChangedEvent"
object eventObj = fieldInfo.GetValue(this);
// eventInfo.ToString() = "System.Object"
PropertyInfo propInfo = typeof(RichTextBox).GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);
// propInfo.ToString() = "System.ComponentModel.EventHandlerList Events"
EventHandlerList list = (EventHandlerList)propInfo.GetValue(this, null);
// list.ToString() = "System.ComponentModel.EventHandlerList"
...
Now at this point I could just call;
list.RemoveHandler(eventObj, list[eventObj]);
and there would be no exceptions but I believe it is silently failing, because if i try to access the delegate as so;
list[eventObj].ToString()
I get a NullReferenceException as there is no such object key in the EventHandlerList. I am calling UnsubscribeUserPreferenceChanged() after MyTextBox has become visible so the handler should be in the list by then as it is added in OnHandleCreated for the RichTextBox.
Anyone got any pointers on how to unsubscribe a SystemEvent hooked to a private event handler in a super class?