提问人:greg 提问时间:10/13/2023 更新时间:10/13/2023 访问量:33
检查 vb.net 控制事件的所有事件订阅者
Examine all the event subscribers to a vb.net control event
问:
我有一种情况,一个事件似乎被调用了两次。
我们正在代码中构建控件,因此最可能的原因是我无意中添加了两次事件处理程序。
对代码的简单检查并不能解决问题。
我希望能够看到按钮。单击并查看向 OnClick 事件添加了多少个例程。
我以为这将是一件简单的事情,但我没有看到任何想要报告不同事件的订阅者的财产。
有什么想法吗?
答:
1赞
dbasnett
10/13/2023
#1
试一试。有一个指向原始代码的链接。要进行测试,您需要一个表单和一个按钮。
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim _delegates As [Delegate] = GetEventHandler(Button1, "EventClick")
If _delegates IsNot Nothing Then
For Each d As [Delegate] In _delegates.GetInvocationList
Debug.WriteLine(d.Method.Name)
Next
End If
End Sub
Private Sub Button1_FOO_(sender As Object, e As EventArgs) Handles Button1.Click
End Sub
' from https://www.vbforums.com/showthread.php?525533-Retrieving-the-EventHandler-for-any-Event-by-code&p=3246140&viewfull=1#post3246140
Private Function GetEventHandler(ByVal ctrl As Control, ByVal eventname As String) As [Delegate]
Dim propInfo As System.Reflection.PropertyInfo
propInfo = GetType(System.ComponentModel.Component).GetProperty("Events", Reflection.BindingFlags.NonPublic Or
Reflection.BindingFlags.Instance Or
Reflection.BindingFlags.Static)
Dim handlerList As System.ComponentModel.EventHandlerList
handlerList = CType(propInfo.GetValue(ctrl, Nothing), System.ComponentModel.EventHandlerList)
Dim controlEventInfo As System.Reflection.FieldInfo
controlEventInfo = GetType(Control).GetField(eventname, Reflection.BindingFlags.NonPublic Or
Reflection.BindingFlags.Static)
If controlEventInfo Is Nothing Then
Return Nothing
' Throw New ArgumentException("Specified event does not exist.")
End If
Dim eventKey As Object = controlEventInfo.GetValue(ctrl)
Dim EventHandlerDelegate As [Delegate] = handlerList.Item(eventKey)
Return EventHandlerDelegate
End Function
End Class
评论
0赞
greg
10/13/2023
谢谢。我没有在谷歌上搜索正确的东西。非常感谢。
评论