我有一个设置为执行任务的后台工作控件,并使用委托过程更新我的主 UI 上的多行文本框。这一切都很完美,但是一旦更新从文本框的底部滚动出来,就会出现滚动条,但是持续刷新会导致文本框保持锁定在顶部。理想情况下,我希望文本框自动滚动到底部以实时显示最新条目。实现这一点的最佳方法是什么?
我尝试过使用该scrolltocaret()
方法,无论SelectionStart = txtlog.Text.Length
前面有没有命令。也许我把它放在错误的地方?
下面的一些代码示例:
委托代码:
Delegate Sub updateresults_delegate(ByVal textbox As TextBox, ByVal text As String)
Private Sub updatelog_threadsafe(ByVal textbox As TextBox, ByVal text As String)
If textbox.InvokeRequired Then
Dim mydelegate As New updateresults_delegate(AddressOf updatelog_threadsafe)
Me.Invoke(mydelegate, New Object() {textbox, text})
'Me.txtlog.SelectionStart = txtlog.Text.Length
'Me.txtlog.ScrollToCaret()
Else
textbox.Text = text
End If
End Sub
主要后台工作者活动:
For i As Integer = val1 To val2
'generate an IP address from split host parts and current value of i
host = s1(0) & "." & s1(1) & "." & s1(2) & "." & i
Try 'attempt to ping the IP
Dim reply As PingReply = pingsender.Send(host, timeoutval, buffer, options)
If reply.Status = IPStatus.Success Then
name = System.Net.Dns.GetHostEntry(host)'get DNS entry
resulttext += String.Format("{1} - {2}: reply: Bytes={3} time{4} TTL={5}{0}", vbCrLf, name.HostName, reply.Address.ToString, reply.Buffer.Length, getms(reply.RoundtripTime), reply.Options.Ttl) 'print out success text
Else
resulttext += String.Format(" {1}: Ping failed. {2}{0}", vbCrLf, host, reply.Status.ToString) 'print out fail text
End If
updatelog_threadsafe(txtlog, resulttext) 'send text to textbox
System.Threading.Thread.Sleep(1000)
Catch ex As Exception
End Try
Next
我想我的主要问题是:我很确定这textbox.scrolltocaret()
是我想要的正确方法,但我把它放在哪里最好?我已经在委托、主要后台工作人员以及方法之前和之后进行了尝试runworkerasync()
。这些都不起作用,现在我很难过!