DataRecieved事件中的关闭表单

时间:2016-12-14 15:34:41

标签: vb.net winforms serial-port

我有从串口捕获十六进制代码的表单。我想在捕获十六进制后立即关闭表单。但我收到错误,无法关闭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

接近这个并关闭表格的正确方法是什么?

感谢

1 个答案:

答案 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线程调用给定的方法。