Imports System.Windows.Forms

Namespace DebugLog
    ''' <summary>
    ''' 考虑修改为自定义控件
    ''' </summary>
    Public Class ControlRecord

        Sub New(recordControl As RichTextBox)
            ShowRecord = True
            SuspendLayout = False
            MaxRecordCount = 512
            RtxRecord = recordControl
        End Sub

        ''' <summary>
        ''' 是否在添加内容时先挂起布局
        ''' </summary>
        ''' <returns></returns>
        Property SuspendLayout() As Boolean

        ''' <summary>
        ''' 是否添加记录到控件
        ''' </summary>
        ''' <returns></returns>
        Property ShowRecord() As Boolean

        ''' <summary>
        ''' 控件记录最大行数
        ''' </summary>
        ''' <returns></returns>
        Property MaxRecordCount() As Integer


        ''' <summary>
        ''' 需要被添加数据记录的控件句柄
        ''' </summary>
        ''' <returns></returns>
        Property RtxRecord() As RichTextBox

        ''' <summary>
        ''' 清空内容
        ''' </summary>
        Public Sub Clear()
            If RtxRecord Is Nothing Then Return
            RtxRecord.Clear()
        End Sub

        Public Sub AppendRecord(logString As String)
            If ShowRecord = False Then Return
            If RtxRecord Is Nothing Then Return

            If RtxRecord.InvokeRequired Then '判断是否需要开委托
                RtxRecord.Invoke(New Action(Of String)(AddressOf AppendRecord), New Object() {logString})
                Return
            End If

            With RtxRecord
                If SuspendLayout Then
                    .SuspendLayout()

                    If .Lines.Length > MaxRecordCount Then '超过上限则移除最初行内容
                        .ReadOnly = False
                        .SelectionStart = 0
                        .SelectionLength = .GetFirstCharIndexFromLine(1)
                        .SelectedText = String.Empty
                        .ReadOnly = True
                        .SelectionStart = .TextLength
                    End If

                    .AppendText($"{Now:yyyy:MM:dd HH:mm:ss} - {logString}{vbNewLine}")

                    .ScrollToCaret()

                    .ResumeLayout(False)
                Else
                    If .Lines.Length > MaxRecordCount Then '超过上限则移除最初行内容
                        .ReadOnly = False
                        .SelectionStart = 0
                        .SelectionLength = .GetFirstCharIndexFromLine(1)
                        .SelectedText = String.Empty
                        .ReadOnly = True
                        .SelectionStart = .TextLength
                    End If

                    .AppendText($"{Now:yyyy:MM:dd HH:mm:ss} - {logString}{vbNewLine}")

                    .ScrollToCaret()

                End If
            End With
        End Sub

    End Class
End Namespace