首页 > 解决方案 > 是否有快速的方法或软件来查看 C# Window Form 事件的触发顺序?

问题描述

目前,没有任何方法或软件可以知道所有事件的顺序以及在C#Windows 窗体中触发的条件。我需要一一尝试。有什么方法可以快速知道事件的触发顺序和条件吗?

标签: c#events

解决方案


据我了解您的问题,您可能要问的是StackTrace

C# 有一个名为 的类System.Diagnostics.StackTrace,它表示堆栈跟踪,它是一个或多个堆栈帧的有序集合。

这是 Microsoft 的一个示例,如何使用它:

class StackTraceSample
{
    [STAThread]
    static void Main(string[] args)
    {
        StackTraceSample sample = new StackTraceSample();
        try
        {
            sample.MyPublicMethod();
        }
        catch (Exception)
        {
            // Create a StackTrace that captures
            // filename, line number, and column
            // information for the current thread.
            StackTrace st = new StackTrace(true);
            for(int i =0; i< st.FrameCount; i++ )
            {
                // Note that high up the call stack, there is only
                // one stack frame.
                StackFrame sf = st.GetFrame(i);
                Console.WriteLine();
                Console.WriteLine("High up the call stack, Method: {0}",
                    sf.GetMethod());

                Console.WriteLine("High up the call stack, Line Number: {0}",
                    sf.GetFileLineNumber());
            }
        }
    }

    public void MyPublicMethod () 
    { 
        MyProtectedMethod(); 
    }

    protected void MyProtectedMethod ()
    {
        MyInternalClass mic = new MyInternalClass();
        mic.ThrowsException();
    }

    class MyInternalClass
    {
        public void ThrowsException()
        {
            try
            {
                throw new Exception("A problem was encountered.");
            }
            catch (Exception e)
            {
                // Create a StackTrace that captures filename,
                // line number and column information.
                StackTrace st = new StackTrace(true);
                string stackIndent = "";
                for(int i =0; i< st.FrameCount; i++ )
                {
                    // Note that at this level, there are four
                    // stack frames, one for each method invocation.
                    StackFrame sf = st.GetFrame(i);
                    Console.WriteLine();
                    Console.WriteLine(stackIndent + " Method: {0}",
                        sf.GetMethod() );
                    Console.WriteLine(  stackIndent + " File: {0}", 
                        sf.GetFileName());
                    Console.WriteLine(  stackIndent + " Line Number: {0}",
                        sf.GetFileLineNumber());
                    stackIndent += "  ";
                }
                throw e;
            }
        }
    }
}

但是由于优化期间发生的代码转换, StackTrace可能不会像预期的那样报告尽可能多的方法调用。

您可以在MSDN 页面上阅读 StackTrace 的详细信息


推荐阅读