リフレクションを使用してInternetExplorerBHOのMSHTMLオブジェクトに.NETイベントハンドラーをインストールするコードがありますが、正常に機能しているようです。しかし、イベントハンドラーを削除しようとすると、問題が発生します。
イベントハンドラのインストールと削除のコードは次のようになります。
public class HandlerExample {
private static void Handler(IHTMLEventObj e) { ... }
private static Delegate handlerDelegate;
public static void InstallHandler(IHTMLElement target, string eventName)
{
// FindInterface() finds the correct event interface for the particular subclass of
// IHTMLElement that target really is
Type eventInterface = FindInterface(target);
EventInfo eInfo = eventInterface.GetEvent(eventName);
Type tHandler = eInfo.EventHandlerType;
handlerDelegate = Delegate.CreateDelegate(tHandler, typeof(HandlerExample), "Handler");
eInfo.AddEventHandler(target, handlerDelegate);
}
public static void RemoveHandler(IHTMLElement target, string eventName)
{
Type eventInterface = FindInterface(target);
EventInfo eInfo = eventInterface.GetEvent(eventName);
eInfo.RemoveEventHandler(target, handlerDelegate); // THIS LINE CRASHES
}
}
の呼び出しはInstallEventHandler
正常に機能Handler
し、ブラウザでイベントがトリガーされると呼び出されます。呼び出しRemoveEventHandler
と同じ引数を使用してInstallEventHandler
呼び出すと、最後の行はTargetInvocationException
、内部例外を除いて、をスローしNullReferenceException
ます。ここで何が間違っているのか理解できず、スタックトレースはあまり役に立ちません。
編集:デバッガーでコードをステップ実行しましたが、直接参照するオブジェクト変数はどれもnullではありません。
また、InstallHandlerメソッドとの両方を呼び出してみましたが、これは正しく機能しAddEventHandler
ます。RemoveEventHandler
スタックトレースは次のとおりです。
System.Reflection.TargetInvocationExceptionが発生しました Message="呼び出しのターゲットによって例外がスローされました。" Source = "mscorlib" スタックトレース: System.RuntimeMethodHandle._InvokeMethodFast(Object target、Object [] arguments、SignatureStruct&sig、MethodAttributes methodAttributes、RuntimeTypeHandle typeOwner)で System.RuntimeMethodHandle.InvokeMethodFast(Object target、Object [] arguments、Signature sig、MethodAttributes methodAttributes、RuntimeTypeHandle typeOwner)で System.Reflection.RuntimeMethodInfo.Invoke(Object obj、BindingFlags invokeAttr、バインダーバインダー、Object []パラメーター、CultureInfoカルチャ、ブールskipVisibilityChecks) System.Reflection.RuntimeMethodInfo.Invoke(Object obj、BindingFlags invokeAttr、バインダーバインダー、Object []パラメーター、CultureInfoカルチャ) System.Reflection.EventInfo.RemoveEventHandler(オブジェクトターゲット、デリゲートハンドラー)で RemoveHandler(IHTMLElement target、String eventName)で InnerException:System.NullReferenceException Message="オブジェクト参照がオブジェクトのインスタンスに設定されていません。" Source = "Microsoft.mshtml" スタックトレース: mshtml.HTMLTextContainerEvents2_EventProvider.remove_onclick(HTMLTextContainerEvents2_onclickEventHandler)で mshtml.HTMLTextAreaElementClass.HTMLTextContainerEvents2_Event_remove_onclick(HTMLTextContainerEvents2_onclickEventHandler)で InnerException:
これを引き起こしている可能性があり、どうすれば修正できますか?