Jos*_*shL 30 c# debugging events visual-studio-2008
我有一个不会关闭的WinForms表单.在OnFormClosing中,e.Cancel设置为true.我猜我的应用程序中的某些对象已绑定到Closing或FormClosing事件,并阻止关闭.为了找到答案,我想确定哪些代表与其中一个事件绑定.
有没有办法确定绑定到事件的处理程序列表?理想情况下,我会通过Visual Studio调试器执行此操作,但可以在应用程序中编写代码以在必要时查找处理程序.理解一个事件就像一个隐藏的私有字段,我已经通过调试器导航到我的表单的"Windows.Forms.Form"祖先的"非公共字段",但无济于事.
Mar*_*ell 33
简而言之,您不打算这样做 - 但是出于调试目的......
事件通常由私人领域支持 - 但不是由控制支持; 他们使用这种EventHandlerList
方法.您必须访问表单的受保护Events
成员,查找映射到(私有)EVENT_FORMCLOSING对象的对象.
一旦你有了FormClosingEventHandler
,GetInvocationList
应该做的工作.
using System;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Forms;
class MyForm : Form
{
public MyForm()
{ // assume we don't know this...
Name = "My Form";
FormClosing += Foo;
FormClosing += Bar;
}
void Foo(object sender, FormClosingEventArgs e) { }
void Bar(object sender, FormClosingEventArgs e) { }
static void Main()
{
Form form = new MyForm();
EventHandlerList events = (EventHandlerList)typeof(Component)
.GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance)
.GetValue(form, null);
object key = typeof(Form)
.GetField("EVENT_FORMCLOSING", BindingFlags.NonPublic | BindingFlags.Static)
.GetValue(null);
Delegate handlers = events[key];
foreach (Delegate handler in handlers.GetInvocationList())
{
MethodInfo method = handler.Method;
string name = handler.Target == null ? "" : handler.Target.ToString();
if (handler.Target is Control) name = ((Control)handler.Target).Name;
Console.WriteLine(name + "; " + method.DeclaringType.Name + "." + method.Name);
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
32744 次 |
最近记录: |