我有从串口捕获十六进制代码的表单。我想在捕获十六进制后立即关闭表单。但我收到错误,无法关闭recyclerView
事件中的表单。
我的代码:
DataReceived
错误:
Public hex As String
Dim sp As SerialPort
Private Sub SerialPort1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim t_hex As String = sp.ReadLine()
If Len(t_hex) < 21 Then
Exit Sub
End If
t_hex = Mid(t_hex, 11, 11)
hex = t_hex
sp.Close()
Me.Close() '' ERROR LINE
End Sub
接近这个并关闭表格的正确方法是什么?
感谢
答案 0 :(得分:0)
找到了答案:
Public hex As String
Dim sp As SerialPort
Private Sub SerialPort1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim t_hex As String = sp.ReadLine()
If Len(t_hex) < 21 Then
Exit Sub
End If
t_hex = Mid(t_hex, 11, 11)
hex = t_hex
sp.Close()
CloseMe()
End Sub
Private Sub CloseMe()
If Me.InvokeRequired Then
Me.Invoke(New MethodInvoker(AddressOf CloseMe))
Exit Sub
End If
Me.Close()
End Sub
编辑:
第一个代码的问题是我在另一个线程内调用Win Forms线程中的方法。所以换句话说,DataReceived
事件在另一个线程中运行,结果我不能在该线程中使用Me.Close()
。
如果你在UI线程以外的任何线程上,InvokeRequired
属性返回true,Invoke
方法从UI线程调用给定的方法。