gpt4 book ai didi

vb.net - 如何在 VB 中加载窗体窗口后运行函数/子?

转载 作者:行者123 更新时间:2023-12-04 05:44:16 24 4
gpt4 key购买 nike

我有一个从 USB 徽章读取器获取用户 ID 的功能,用于登录应用程序。当我运行该应用程序时,在我滑动标签之前不会出现登录窗口。我需要知道是否可以加载窗口,然后开始运行从 USB 获取数据的函数。

谢谢:)

Private Sub SerialPort1_DataReceived()
'Threading.Thread.SpinWait(1000)
OpenPort()
If SerialPort1.IsOpen() Then

byteEnd = SerialPort1.NewLine.ToCharArray
'read entire string until .Newline
readBuffer = SerialPort1.ReadLine()
readBuffer = readBuffer.Remove(0, 1)
readBuffer = readBuffer.Remove(8, 1)
WWIDTextBox.AppendText(readBuffer)

End If
End Sub

Private Sub Form1_Activated(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Activated
SerialPort1_DataReceived()
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'SerialPort1_DataReceived()
End Sub

最佳答案

问题是您正在调用 ReadLine 方法,这是一个阻塞(同步)方法。换句话说,当您调用它时,该方法只有在具有要返回的值后才会返回值。因此,它会停止在当前线程上执行,直到读取完整的一行(当徽章被刷过时)。由于您在调用它时处于 UI 线程上,因此它会锁定 UI,直到徽章被刷过。

无需从 UI 线程调用 SerialPort1_DataReceived 方法,您可以从不同的线程完成这项工作。最简单的方法是将 BackgroundWorker 组件拖到设计器中的窗体上。然后你可以添加这样的代码:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
BackgroundWorker1.RunWorkerAsync()
End Sub

Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
OpenPort()
If SerialPort1.IsOpen() Then
byteEnd = SerialPort1.NewLine.ToCharArray
Dim readBuffer As String = SerialPort1.ReadLine()
readBuffer = readBuffer.Remove(0, 1)
readBuffer = readBuffer.Remove(8, 1)
e.Result = readBuffer
End If
End Sub

Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
WWIDTextBox.AppendText(CStr(e.Result))
End Sub

关于vb.net - 如何在 VB 中加载窗体窗口后运行函数/子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15974936/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com