How to get the current line number at break/except

2019-05-07 03:21发布

I'm messing around with the Visual Studio add-in API trying to see if something I want to do is possible. One thing I am doing right now is something like:

    public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
    {
        _applicationObject.Events.DebuggerEvents.OnExceptionThrown += DebuggerEvents_OnExceptionThrown;
        handled = false;
        if(executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
        {
            if(commandName == "MyAddin1.Connect.MyAddin1")
            {
                handled = true;
                return;
            }
        }
    }

    void DebuggerEvents_OnExceptionThrown(string ExceptionType, string Name, int Code, string Description, ref dbgExceptionAction ExceptionAction)
    {
        //how to get line number here?
    }

Ideally, I'd like to be able to get the current function and line number whenever an exception is thrown by a program being debugged. Is this possible?

1条回答
\"骚年 ilove
2楼-- · 2019-05-07 04:00

This information is apparently lifted from the debug information. As such, it isn't always available, I guess this is why it makes sense for the StackFrames object to not implement it in this case.

Anyway, to get a stack trace with file and line number information(and IL offset, etc) you have to dynamically execute code within the debugged application's context. You can do this using GetExpression.

In summary:

var tmp = dte.Debugger.GetExpression(
    "new System.Diagnostics.StackTrace(true).ToString();", true);

This will return a string with the stack trace, including file and line numbers... However, you must parse this returned string to actually make use of it, and I assume that this is much slower than the more common method

查看更多
登录 后发表回答