如何设置基本的VB.NET WinForms应用程序

Unk*_*own 2 vb.net error-handling

我想写一个专业的转售申请表.我需要知道如何设置一个有效的错误处理WinForms应用程序?

小智 5

创建一个抛光的应用程序并不是一项微不足道的任务.这需要很多时间和经验.

通过处理"未处理的"线程和域异常,可以在.NET中进行有效的错误处理.

以下代码是执行此操作的应用程序的示例.您需要派生自己的Form实例.

购买一本关于这个主题的好书也是学习如何做到这一点的有效方法.


Module modMain

    Public Sub Log(ByVal ex As Exception)

        Try

            Dim logDirectory As String = IO.Path.Combine(Application.StartupPath, "Log")
            Dim logName As String = DateTime.Now.ToString("yyyyMMdd") & ".txt"
            Dim fullName As String = IO.Path.Combine(logDirectory, logName)

            If Not IO.Directory.Exists(logDirectory) Then
                IO.Directory.CreateDirectory(logDirectory)
            End If

            Dim errorString As String = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss") & " >> " & _
                                        ex.Message & Environment.NewLine & _
                                        ex.StackTrace & Environment.NewLine

            IO.File.AppendAllText(fullName, errorString)

        Catch ignore As Exception

        End Try

    End Sub

    Public Sub ThreadExceptionHandler(ByVal sender As Object, ByVal e As Threading.ThreadExceptionEventArgs)
        Log(e.Exception)
    End Sub

    Public Sub DomainExceptionHandler(ByVal sender As Object, ByVal e As System.UnhandledExceptionEventArgs)
        Dim ex As Exception = CType(e.ExceptionObject, Exception)
        Log(ex)
    End Sub

    Public Sub Main()

        AddHandler Application.ThreadException, AddressOf ThreadExceptionHandler
        Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException)

        AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf DomainExceptionHandler

        Try
            Application.Run(New Form)
        Catch ex As Exception
            Log(ex)
        Finally
            RemoveHandler Application.ThreadException, AddressOf ThreadExceptionHandler
            RemoveHandler AppDomain.CurrentDomain.UnhandledException, AddressOf DomainExceptionHandler
        End Try

    End Sub

End Module
Run Code Online (Sandbox Code Playgroud)