如何从其他表单中删除Handler一个委托 [英] How to RemoveHandler a Delegate from other form
本文介绍了如何从其他表单中删除Handler一个委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
每个人
i有两种形式
Form1和Form2
in form2我有一个活动
Hi every one
i have two forms
Form1 and Form2
in form2 i have a event
Public Class Form2
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MsgBox("This is form2")
End Sub
End Class
现在我想在调用之前删除handler Form2_Load它是
i发现此代码用于获取加载代理
now i want to removehandler Form2_Load before call it
i found this code for get load delegate
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)
但是当removehandler无效时
but when removehandler not works on that
RemoveHandler FRM2.Load, dEmitted
FRM2.ShowDialog()
i尝试这段代码,但它不起作用
i try this code but it''s not work too
evClick.RemoveEventHandler(FRM2, dEmitted)
FRM2.ShowDialog()
我的问题在哪里m?
谢谢。
Where is my problem?
thank you.
推荐答案
代表与否,这并不重要。
这是关于表单协作的热门问题。最强大的解决方案是在表单类中实现适当的接口,并传递接口引用而不是引用Form的整个实例。有关更多详细信息,请参阅我以前的解决方案:如何以两种形式复制列表框之间的所有项目 [ ^ ]。
另请参阅:
http://en.wikipedia.org/wiki/Accidental_complexity [ ^ ],
http://en.wikipedia.org/wiki/Loose_coupling [ ^ ]。
-SA
Delegate or not, it does not really matter.
This is the popular question about form collaboration. The most robust solution is implementation of an appropriate interface in form class and passing the interface reference instead of reference to a "whole instance" of a Form. Please see my past solution for more detail: How to copy all the items between listboxes in two forms[^].
Please see also:
http://en.wikipedia.org/wiki/Accidental_complexity[^],
http://en.wikipedia.org/wiki/Loose_coupling[^].
—SA
这篇关于如何从其他表单中删除Handler一个委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文