VB.NET ThreadingException Bypass When Sub Main Is Not Available

I have a winforms VB.NET solution, and I would like to add standard application exception handlers - Application.ThreadExceptionand AppDomain.CurrentDomain.UnhandledException.

I have the following code from MSDN

' Starts the application. '
<SecurityPermission(SecurityAction.Demand, Flags:=SecurityPermissionFlag.ControlAppDomain)> _
Public Shared Sub Main()
    ' Add the event handler for handling UI thread exceptions to the event. '
    AddHandler Application.ThreadException, AddressOf ErrorHandlerForm.Form1_UIThreadException

    ' Set the unhandled exception mode to force all Windows Forms errors to go through'
    ' our handler. '
    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException)

    ' Add the event handler for handling non-UI thread exceptions to the event. '
    AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf CurrentDomain_UnhandledException

    ' Runs the application. '
    Application.Run(New ErrorHandlerForm())
End Sub

How can I do this in VB.NET when I do not have access to the method Sub Main()?

This is the case when the “Enable application platform” option of my solution properties is enabled ( Sub Mainhidden) ...

+3
source share
2 answers

You can catch the My.Application.Startup event to add the code that needs to be run before any forms load.

, Startup ApplicationEvents.vb, .

EDIT: , My.Application System.Windows.Forms.Application. . System.Windows.Forms, - .

+1

, - , Imports . Import, , :

Imports System
Imports System.Windows.Forms

Public Shared Sub MyApplicationInitialization()
    AddHandler System.Windows.Forms.Application.ThreadException, AddressOf MyThreadExceptionHandler

    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException)

    AddHandler System.AppDomain.CurrentDomain.UnhandledException, AddressOf MyUnhandledExceptionHandler
End Sub

, AppDomain System Application System.Windows.Forms.

, , AddressOf. :

Sub MyUnhandledExceptionHandler(ByVal sender As Object, ByVal e As UnhandledExceptionEventArgs)
    'your logic here
End Sub

Sub MyThreadExceptionHandler(ByVal sender As Object, ByVal e As ThreadExceptionEventArgs)
    'your logic here
End Sub
+1

All Articles