请教SerialPort1_DataReceived调用委托之后,关闭窗口时卡死
Public Class Form1
Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
SerialPort1.Close()
End Sub
Private Sub Form1_Load_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SerialPort1.BaudRate = "9600" '波特率
SerialPort1.PortName = "COM3" '串口名称
SerialPort1.DataBits = 8 '数据位
SerialPort1.StopBits = IO.Ports.StopBits.One '停止位
SerialPort1.Parity = IO.Ports.Parity.None '校验位
'SerialPort1.Open() '打开串口
GroupBox2.Enabled = False
'初始化下拉串口名称列表框
Dim ports As String() = IO.Ports.SerialPort.GetPortNames()
Array.Sort(ports)
ComboBox1.Items.AddRange(ports)
ComboBox1.SelectedIndex = If(ComboBox1.Items.Count > 0, 0, -1)
Label3.Text = Format(Now, "yyy") + "年" + Format(Now, "m")
End Sub
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'根据当前串口对象,来判断操作
If SerialPort1.IsOpen Then
'打开时点击,则关闭串口
SerialPort1.Close()
GroupBox2.Enabled = False
Timer1.Enabled = False
Else
'关闭时点击,则设置好端口,波特率后打开
SerialPort1.PortName = ComboBox1.Text
Try
SerialPort1.Open()
GroupBox2.Enabled = True
Timer1.Enabled = True
Catch ex As Exception
'捕获到异常信息
SerialPort1 = New IO.Ports.SerialPort()
'显示异常信息给客户。
MessageBox.Show(ex.Message)
End Try
End If
'设置按钮的状态
Button1.Text = If(SerialPort1.IsOpen, "关闭", "打开")
' Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)
'将16进制转换成10进制
' value = (Val("&H" & datastr(1)) * (16 ^ 1) + Val("&H" & datastr(2)) * (16 ^ 0)) / 255 * 5.0
' data10.Text = value '进制显示,保留一位小数
' num = num + 1 '采集个数
' Call draw() '调用绘曲线过程
' SerialPort1.Write(value)
End Sub
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim n As Integer = SerialPort1.BytesToRead
Dim a As UInt16, c As UInt16
Dim buf(n) As Byte '声明一个临时数组存储当前来的串口数据
Dim b(2) As Byte
SerialPort1.Read(buf, 0, n) '读取缓冲数据
For a = 0 To n
If buf(a) = "35" Then
Exit For
End If
Next
If n >= (a + 2) Then
If buf(a + 2) = "42" Then
For c = 0 To 2
b(c) = buf(a + c)
Next
Invoke(Sub()
startchar.Text = b(0)
TextBox1.Text = b(1)
stopchar.Text = b(2)
End Sub)
End If
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
SerialPort1.Close()
End
End Sub
End Class
怎么解决这个问题呢,程序功能就是接受下位机传来的“# AD值 *”这3个字节,#表示开始字符,*表示结束字符,调用委托之后,凡是点击关闭串口,还是点击窗口关闭都会卡死界面
能不能再给个不用SerialPort1_DataReceived事件,只用timer来做的程序呢,或者教教方法也可以 异常 对象 C SerialPort1 timer --------------------编程问答-------------------- 闭关时候要让线程等一下,有需要还要先清除数据的。
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'SerialPort1.DiscardOutBuffer() 有需要时,清除数据。
SerialPort1.Close()
Threading.Thread.Sleep(10)
End Sub
补充:.NET技术 , VB.NET