查找 .NET 中 Windows 窗体控件的所有事件处理程序
有没有办法找到 Windows 窗体 控件的所有事件处理程序?具体静态定义的事件处理程序?
Is there a way to find all event handlers for a Windows Forms control? Specifically statically defined event handlers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Windows 窗体有强有力的对策来防止这样做。大多数控件将事件处理程序引用存储在需要秘密“cookie”的列表中。 cookie 值是动态创建的,您无法预先猜测它。反射是一个后门,你必须知道cookie变量名。例如,Control.Click 事件的名称为“EventClick”,您可以在参考源中或使用 Reflector 看到这一点。
这一切都是非常不切实际的,如果你感觉自己在做一些不明智的事情,那么你就走在正确的轨道上。您可以在我的答案中找到执行此操作的示例代码 此线程。
Windows Forms has strong counter-measures against doing this. Most controls store the event handler reference in a list that requires a secret 'cookie'. The cookie value is dynamically created, you cannot guess it up front. Reflection is a backdoor, you have to know the cookie variable name. The one for the Control.Click event is named "EventClick" for example, you can see this in the Reference Source or with Reflector.
This is all incredibly unpractical, if you're getting the feeling you are doing something unwise then you're on the right track. You can find sample code that does this in my answer in this thread.
Windows 窗体控件使用
EventHandlerList
名为Events
< 的属性/a> 保存事件处理程序,以便您可以迭代该集合。要确定哪些订阅的处理程序是静态的,您需要使用反射。Windows Forms controls use an
EventHandlerList
property calledEvents
to hold event handlers so you could iterate that collection. To determine which subscribed handlers are static, you will need to use reflection.此代码将获取控件的事件处理程序
我在多次添加事件处理程序时遇到问题,导致多个引发事件。下面将允许您检查控件是否已经具有指定事件的处理程序。
This code will get the event handlers for a control
I have had problems with adding event handlers more than once resulting in multiple raised events. The following will allow you to check whether a control already has a handler for a specified event.