Alternar “Break cuando se produce una excepción.” Macro o utilizando el teclado de acceso directo

StackOverflow https://stackoverflow.com/questions/958011

Pregunta

  

Editar: nueva ventana excepción de Visual Studio 2015 es mucho más rápido que   la edad de diálogo que ya no importa tanto que ver con el uso de un teclado   acceso directo a él.

¿Hay un atajo macro o teclado que se alternará "romperse cuando se produce una excepción" sin usar la interfaz gráfica de usuario?

La apertura del diálogo con Ctrl + Alt + E y la comprobación de las "excepciones" Common Language Runtime "Arrojado" cuadro a continuación, hacer clic en OK es bastante simple, pero esto es algo que hago mucho. Yo preferiría tener un atajo de teclado para esto.

Esta pregunta es un duplicado de Cualquier tienen un Visual estudio acceso directo / macro para alternar descanso en excepciones manejadas / no controladas?

Sin embargo, el cartel aceptado una respuesta que no funciona muy bien, y me gusta mucho una respuesta que hace trabajo.

La respuesta en la pregunta duplicado no es aceptable, ya que cambia solamente una excepción específica, no todo el grupo CLR.

"Bien escribir un bucle a continuación." tu dices. Pero no tan rápido! Alguien intentó que ya y fue inútilmente lenta. (Sí, lo he verificado que su lento en mi sistema, así.)

Así que el reto es utilizar una macro para cambiar toda la categoría de excepciones CLR en menos de 1 o 2 segundos. Esta pregunta es un duplicado de Cualquier tienen un Visual estudio acceso directo / macro para alternar descanso en excepciones manejadas / no controladas?

¿Fue útil?

Solución

He creado una extensión de Visual Studio libre que puede hacerlo de forma fiable: excepción disyuntor.
Utiliza llamada IDebugSession2.SetException indocumentado que es muy rápido:. Todas las excepciones se establecen / desarmado de 20 a 60 milisegundos

Otros consejos

Muy similar a la otra respuesta, pero hay una ExceptionSetting especial para el grupo.

Dim dbg As EnvDTE90.Debugger3 = DTE.Debugger
Dim exSettings As EnvDTE90.ExceptionSettings = dbg.ExceptionGroups.Item("Common Language Runtime Exceptions")
Dim exSetting As EnvDTE90.ExceptionSetting
Try
    exSetting = exSettings.Item("Common Language Runtime Exceptions")
Catch ex As COMException
    If ex.ErrorCode = -2147352565 Then
        exSetting = exSettings.NewException("Common Language Runtime Exceptions", 0)
    End If
End Try

If exSetting.BreakWhenThrown Then
    exSettings.SetBreakWhenThrown(False, exSetting)
Else
    exSettings.SetBreakWhenThrown(True, exSetting)
End If

Esto es muy útil macro de Bryce Kahle ciegamente actualizado para funcionar en VS2010:

Sub ToggleExceptions()
    Dim dbg As EnvDTE100.Debugger5 = DTE.Debugger
    Dim exSettings As ExceptionSettings = dbg.ExceptionGroups.Item("Common Language Runtime Exceptions")
    Dim exSetting As ExceptionSetting
    Try
        exSetting = exSettings.Item("Common Language Runtime Exceptions")
    Catch ex As COMException
        If ex.ErrorCode = -2147352565 Then
            exSetting = exSettings.NewException("Common Language Runtime Exceptions", 0)
        End If
    End Try

    If exSetting.BreakWhenThrown Then
        exSettings.SetBreakWhenThrown(False, exSetting)
    Else
        exSettings.SetBreakWhenThrown(True, exSetting)
    End If

End Sub

En primer lugar me initalized un temporizador de un entonces yo llamo el Exception.Debug comando. El éxito temporizador, cuando se inagurado el cuadro de diálogo modal. Si utiliza Windows 7 con UAC desactivado SendKeys con ALT-Key se producirá un error ... no sé qué.

he jugado un poco ... este trato (VS2010 ES):

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics
Imports System.Runtime.InteropServices

'...

Private WithEvents t As Timers.Timer
Private Sub t_Elapsed(ByVal ee As Object, ByVal dd As Timers.ElapsedEventArgs) Handles t.Elapsed
    t.Stop()
    ' Tastatureingaben simulieren
    System.Windows.Forms.SendKeys.SendWait("{DOWN}")
    System.Threading.Thread.Sleep(1500) ' Pause wichtig zum Laden des Exceptionbaums
    System.Windows.Forms.SendKeys.SendWait("%t")
    System.Windows.Forms.SendKeys.SendWait("{ENTER}")
End Sub
Public Sub toggleCLRExceptions()
    If DTE.Solution.Count <= 0 Then
        MsgBox("Nicht ohne geöffnete Solution!")
        Exit Sub
    End If
    ' Timer wird benötigt, da der Dialog Modal ist
    ' und weitere Befehle im Macro werden erst nach beenden des Dialogs ausgeführt
    t = New Timers.Timer()
    t.Interval = 0.5
    t.Start()
    DTE.ExecuteCommand("Debug.Exceptions")
    'System.Windows.Forms.SendKeys.SendWait("^%e") ' alternativ: STRG+ALT+e
    System.Threading.Thread.Sleep(200)
    If isCLRExceptionsActive() Then
        MsgBox("BREAK @CLR-Exception", MsgBoxStyle.Information, "Info")
    Else
        MsgBox("NO BREAK @CLR-Exception", MsgBoxStyle.Information, "Info")
    End If
End Sub

Function isCLRExceptionsActive() As Boolean
    ' prüft, ob Setting Debug CLR-Exceptions aktiviert/deaktivert ist
    Dim dbg As EnvDTE100.Debugger5 = DTE.Debugger
    Dim exSettings As ExceptionSettings = dbg.ExceptionGroups.Item("Common Language Runtime Exceptions")
    Dim exSetting As ExceptionSetting
    Try
        exSetting = exSettings.Item("Common Language Runtime Exceptions")
    Catch ex As COMException
        If ex.ErrorCode = -2147352565 Then
            exSetting = exSettings.NewException("Common Language Runtime Exceptions", 0)
        End If
    End Try
    Return exSetting.BreakWhenThrown
End Function

'...

Bueno, me escribió un plug-in VS2008 C # basado que alterna las 386 excepciones, y se tarda aproximadamente 1 segundo por basculador del estado. Asumo que eso es debido a COM inter-op.

Esto se basó en el / código de macro de VB en el uno de sus enlaces. No pude encontrar un método más fácil de C ++ (pero no lo descartamos).

El siguiente nivel sería hacer un plug-in que tiene la unión, que a continuación se abre la interfaz de usuario Excepciones y haga "clic" la casilla correcta para usted un teclado.

Buena suerte.

Se puede utilizar una herramienta como AutoHotKey para crear un script grabado (clics del ratón o pulsaciones de teclas) y luego asignarle una tecla de acceso directo que va a jugar de nuevo cuando se pulsa ...

Al igual que ofrece algo de información que encontré en este ( aquí ) ya que estaba recorriendo la red en mi intento inútil para ayudar ...

Alguien más hizo esta misma pregunta y que fue respondido por Gary Chang desde MS textuales, he aquí la respuesta citado:?

  

Me temo que el código de macro no se   manipular las operaciones en el   cuadro de diálogo excepciones ...

Es importante señalar que este anuncio es de diciembre de 2005 por lo que esta respuesta no puede ser exacta; De cualquier manera, pensé en tirar por ahí.

La sugerencia de establecer el ExceptionSetting especial para el grupo en efecto cambiar el estado de la casilla de verificación de nivel superior. Sin embargo, no parece para cambiar las excepciones individuales por debajo de ella en el árbol, y por otra parte, mi proceso no se detiene cuando tales excepciones son arrojados como lo hace si puedo comprobar manualmente la casilla de verificación de nivel superior. ¿Ves un comportamiento diferente?

Mi macro para ignorar excepción CLR actual en tiempo de ejecución. Funciona como un botón de 'desactivar la captura de este tipo de excepción' cuando aparece una excepción en depuración de tiempo.

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics
Imports Microsoft.VisualBasic
Imports Microsoft.VisualBasic.ControlChars

' execute Macros.MyMacros.VSDebuggerExceptions.IgnoreCurrentExceptionWhenThrown from VS Command Window

Public Module VSDebuggerExceptions

    Sub BreakWhenThrown(Optional ByVal strException As String = "")
        Dim dbg As Debugger3 = DTE.Debugger
        Dim eg As ExceptionSettings = _
            dbg.ExceptionGroups.Item("Common Language Runtime Exceptions")
        eg.SetBreakWhenThrown(True, eg.Item(strException))
    End Sub

    ' copied from Utilities module (samples)
    Function GetOutputWindowPane(ByVal Name As String, Optional ByVal show As Boolean = True) As OutputWindowPane
        Dim window As Window
        Dim outputWindow As OutputWindow
        Dim outputWindowPane As OutputWindowPane

        window = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput)
        If show Then window.Visible = True
        outputWindow = window.Object
        Try
            outputWindowPane = outputWindow.OutputWindowPanes.Item(Name)
        Catch e As System.Exception
            outputWindowPane = outputWindow.OutputWindowPanes.Add(Name)
        End Try
        outputWindowPane.Activate()
        Return outputWindowPane
    End Function

    Private WithEvents t As Timers.Timer

    ' Adds the current exception to ignore list
    Sub IgnoreCurrentExceptionWhenThrown()
        Dim commandWin As EnvDTE.CommandWindow
        commandWin = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindCommandWindow).Object

        Select Case DTE.Debugger.CurrentMode
            Case dbgDebugMode.dbgDesignMode
                commandWin.OutputString("This macro is not enabled in Design Mode. Run it in Break Mode." + vbCrLf)
                Return

            Case dbgDebugMode.dbgRunMode
                commandWin.OutputString("This macro is not enabled in Run Mode. Run it in Break Mode." + vbCrLf)
                Return
        End Select

        commandWin.OutputString(Environment.NewLine)
        commandWin.OutputString("Trying to get the information about current exception.." + Environment.NewLine)

        Dim dbg As Debugger3 = DTE.Debugger
        Dim currentExpression As Expression = dbg.GetExpression("$exception", False)
        Try    
            Dim currentExceptionTypeString As String = currentExpression.DataMembers.Item(1).Type
            commandWin.OutputString("Detected current exception type is : " + currentExceptionTypeString + Environment.NewLine)

            Dim flag As Boolean = True
            Dim eg As ExceptionSettings = dbg.ExceptionGroups.Item("Common Language Runtime Exceptions")
            Try
                eg.SetBreakWhenThrown(False, eg.Item(currentExceptionTypeString))
            Catch exc As Exception
                commandWin.OutputString("Cannot find this exception, trying to create.." + currentExceptionTypeString + Environment.NewLine)
                '
                eg.NewException(currentExceptionTypeString, New Random().Next)
                eg.SetBreakWhenThrown(False, eg.Item(currentExceptionTypeString))
                eg.SetBreakWhenUserUnhandled(True, eg.Item(currentExceptionTypeString))
                flag = False
            End Try

            commandWin.OutputString(Environment.NewLine)
            commandWin.OutputString("Exception '" + currentExceptionTypeString + "' added to ignore list.")
            commandWin.OutputString(Environment.NewLine)

            t = New Timers.Timer()
            ' small interval to send keys after DTE will start to exec command
            t.Interval = 0.1
            t.Start()
            DTE.ExecuteCommand("Debug.Exceptions")

        Catch exc As Exception
            commandWin.OutputString("Error occured")
        End Try
    End Sub

    Private Sub t_Elapsed(ByVal ee As Object, ByVal dd As Timers.ElapsedEventArgs) Handles t.Elapsed
        t.Stop()
        ' only press Ok to apply changed exceptions settings to debugger
        System.Windows.Forms.SendKeys.SendWait("%t")
        System.Windows.Forms.SendKeys.SendWait("{ENTER}")
    End Sub

End Module

CTRL + ALT + E T ALT + Introduzca

funciona para mí

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top