Kyl*_*ons 6 vb.net serial-port visual-studio
我试图只使用代码在VB.net中创建一个串口.因为我正在创建一个类库,所以我无法使用内置组件.我试过实例化一个新的SeialPort()对象,但这似乎还不够.我确信有一些简单的东西我很想念,任何帮助都会非常感激!谢谢!
PS我应该补充一点,我此时遇到的问题是获取处理datareceived事件的代码.除此之外它可能正在起作用,但由于这个问题我无法分辨.
如果要使用事件,请确保使用'withevents'声明serialPort对象.下面的示例将允许您连接到串行端口,并将使用接收的字符串引发事件.
Imports System.Threading
Imports System.IO
Imports System.Text
Imports System.IO.Ports
Public Class clsBarcodeScanner
Public Event ScanDataRecieved(ByVal data As String)
WithEvents comPort As SerialPort
Public Sub Connect()
Try
comPort = My.Computer.Ports.OpenSerialPort("COM5", 9600)
Catch
End Try
End Sub
Public Sub Disconnect()
If comPort IsNot Nothing AndAlso comPort.IsOpen Then
comPort.Close()
End If
End Sub
Private Sub comPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles comPort.DataReceived
Dim str As String = ""
If e.EventType = SerialData.Chars Then
Do
Dim bytecount As Integer = comPort.BytesToRead
If bytecount = 0 Then
Exit Do
End If
Dim byteBuffer(bytecount) As Byte
comPort.Read(byteBuffer, 0, bytecount)
str = str & System.Text.Encoding.ASCII.GetString(byteBuffer, 0, 1)
Loop
End If
RaiseEvent ScanDataRecieved(str)
End Sub
End Class
Run Code Online (Sandbox Code Playgroud)