事件处理程序适用于控制台应用程序,但不适用于表单应用程序

时间:2015-12-01 18:50:58

标签: vb.net visual-studio events

我正在设置一个事件处理程序来响应串行通信。

以下代码运行完美,并将收到的数据显示到控制台

Imports System
Imports System.IO.Ports

Module Module1

    Sub DataReceivedHandler(
                        sender As Object,
                        e As SerialDataReceivedEventArgs)
        Dim sp As SerialPort = CType(sender, SerialPort)
        Threading.Thread.Sleep(500)
        Dim indata As String = sp.ReadExisting()
        Console.Write(indata)
    End Sub

    Sub Main()
        Dim mySerialPort As New SerialPort("COM2")

        mySerialPort.BaudRate = 9600
        mySerialPort.Parity = Parity.None
        mySerialPort.StopBits = StopBits.One
        mySerialPort.DataBits = 8
        mySerialPort.Handshake = Handshake.None
        mySerialPort.RtsEnable = True

        AddHandler mySerialPort.DataReceived, AddressOf DataReceivedHandler

        mySerialPort.Open()

        Console.WriteLine("Press any key to continue...")
        Console.WriteLine()
        Console.ReadKey()
        mySerialPort.Close()
    End Sub

End Module

但是,这个代码完全相同,只是在表单应用程序中运行,但无法显示任何消息。

Imports System.IO.Ports

Public Class Form1


    Sub DataReceivedHandler(
                        sender As Object,
                        e As SerialDataReceivedEventArgs)
        Dim sp As SerialPort = CType(sender, SerialPort)
        Threading.Thread.Sleep(500)
        Dim indata As String = sp.ReadExisting()
        MsgBox(indata)
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim mySerialPort As New SerialPort("COM2")

        mySerialPort.BaudRate = 9600
        mySerialPort.Parity = Parity.None
        mySerialPort.StopBits = StopBits.One
        mySerialPort.DataBits = 8
        mySerialPort.Handshake = Handshake.None
        mySerialPort.RtsEnable = True
        AddHandler mySerialPort.DataReceived, AddressOf DataReceivedHandler
        mySerialPort.Open()
    End Sub

End Class

1 个答案:

答案 0 :(得分:0)

请勿使用MsgBox,请使用Debug.Print

您在一个不是winform app的消息线程的线程上调用MsgBox。