Click here to Skip to main content
15,897,371 members

How to RemoveHandler a Delegate from other form

Sina asefi asked:

Open original thread
Hi every one
i have two forms
Form1 and Form2
in form2 i have a event
VB
Public Class Form2

    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        MsgBox("This is form2")
    End Sub
End Class


now i want to removehandler Form2_Load before call it

i found this code for get load delegate
VB
Dim FRM2 As Form = New Form2
      Dim assem As [Assembly] = [Assembly].GetExecutingAssembly()
      Dim tExForm As Type = assem.GetType("WindowsApplication2.Form2")
      Dim exFormAsObj As Object = _
          Activator.CreateInstance(tExForm)
      Dim evClick As EventInfo = tExForm.GetEvent("Load")
      Dim tDelegate As Type = evClick.EventHandlerType

      Dim handler As New DynamicMethod( _
         "", _
         Nothing, _
         GetDelegateParameterTypes(tDelegate), _
         GetType(Form1) _
     )
      Dim ilgen As ILGenerator = handler.GetILGenerator()

      Dim showParameters As Type() = {GetType(String)}
      Dim simpleShow As MethodInfo = _
          GetType(MessageBox).GetMethod("Show", showParameters)

      ilgen.Emit(OpCodes.Ldstr, _
          "This event handler was constructed at run time.")
      ilgen.Emit(OpCodes.Call, simpleShow)
      ilgen.Emit(OpCodes.Pop)
      ilgen.Emit(OpCodes.Ret)
      Dim dEmitted As [Delegate] = handler.CreateDelegate(tDelegate)


but when removehandler not works on that
VB
RemoveHandler FRM2.Load, dEmitted

       FRM2.ShowDialog()


i try this code but it's not work too
VB
evClick.RemoveEventHandler(FRM2, dEmitted)
FRM2.ShowDialog()


Where is my problem?
thank you.
Tags: C#, Visual Basic, Visual Studio

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900