本文介绍了串行端口通信尝试期间出现空参考异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 Dim withevents COMPort as SerialPort Dim comOpen as Boolean Private Sub Form1_FormClosed(ByVal sender as object,ByVal e As System.Windows.Forms.FormCLosedEventArgs)处理Me.FormClosed 使用COMPORT .POrtName =COM20各种其他属性 以 结束如果COMPort.IsOpen然后 COMPort.Colse()结束如果结束Sub Private Sub Form1_Load(ByVal sender as system.object,ByVal e As System.EventArgs处理MyBAse.Load Dim Portnames as string()= serialPort.GetPortNames 如果Portnames什么都不是 MsgBox(None detected) Me.Close()结束IF cbComPort.Items.AddRange(Portnames) cbComPort.Text = Portnames(0) End Sub Private sub btnConnect_Click( ByVal Sender As System.Object,byval e as System.EventArgs)处理btnConnect.Click 尝试 COMPort.Open() comOpen = ComPort.IsOpen Catch comOpen = False MsgBox( 错误打开:& ex.Message)结束尝试 如果COMport.IsOPen那么'ERROE HERE null引用异常 COMPort.Write(01) 结束如果 End Sub Dim readBuffer as string Private Sub COMPort_DataReceived(ByVal sender as system.Object,ByVal e As SerialDataReceivedEventArgs)HAndles COMPort。 DataReceived 尝试 readBuffer = COMPort.ReadLine() Me.Invoke(New EventHandler(AddressOf DoUpdate)) Catch MsgBox(read & ex.Message) End Try End Sub Public Sub DoUpdate(ByVal sender as Object,Byval e as System.EventArgs) tbRx.text = readBuffer 结束次级 < pre> 所以这就是我到目前为止所拥有的 我尝试了什么: 不完全确定如何解决它。我真的非常需要帮助,我可以告诉每个人都不喜欢这个问题,但我不知道该怎么做。 谢谢解决方案 Dim withevents COMPort as SerialPortDim comOpen as BooleanPrivate Sub Form1_FormClosed(ByVal sender as object, ByVal e As System.Windows.Forms.FormCLosedEventArgs)Handles Me.FormClosedWith COMPort .POrtName = "COM20" various other propertiesEnd withIf COMPort.IsOpen then COMPort.Colse()End IfEnd SubPrivate Sub Form1_Load(ByVal sender as system.object, ByVal e As System.EventArgs)Handles MyBAse.LoadDim Portnames as string() = serialPort.GetPortNamesif Portnames is nothing then MsgBox ("None detected")Me.Close()End IFcbComPort.Items.AddRange(Portnames)cbComPort.Text = Portnames(0)End SubPrivate sub btnConnect_Click(ByVal Sender As System.Object, byval e as System.EventArgs) handles btnConnect.ClickTry COMPort.Open() comOpen = ComPort.IsOpenCatch comOpen = False MsgBox("Error Open: " & ex.Message)End TryIf COMport.IsOPen Then ' ERROE HERE null reference exception COMPort.Write("01")End IfEnd SubDim readBuffer as stringPrivate Sub COMPort_DataReceived(ByVal sender as system.Object, ByVal e As SerialDataReceivedEventArgs) HAndles COMPort.DataReceivedTry readBuffer = COMPort.ReadLine() Me.Invoke(New EventHandler(AddressOf DoUpdate))Catch MsgBox("read " &ex.Message)End TryEnd SubPublic Sub DoUpdate(ByVal sender as Object, Byval e as System.EventArgs)tbRx.text = readBufferEnd Sub<pre>So this is what I have so farWhat I have tried:Not entirely sure how to solve it. I really really really need help, I can tell everyone is going to dislike the question but I don't know what to do.Thanks 解决方案 这篇关于串行端口通信尝试期间出现空参考异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-22 00:31