vb.net - 当我的条形码扫描仪扫描条形码时,我的 textbox1 将收到 System.Windows.Forms.TextBox, Text: 错误消息。有人能帮我吗
问题描述
当我的条形码扫描仪扫描条形码时,在我的文本框中,我会得到
System.Windows.Forms.TextBox,文本:错误消息。
我尝试了很多方法来解决这个问题,但仍然没有成功。有人可以帮我看看吗?谢谢
下面是我的代码
Public Class Form1
Dim dataIn As String
'Dim userText As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SerialPort.PortName = "COM1"
SerialPort.BaudRate = CInt("9600")
SerialPort.Parity = Parity.None
SerialPort.StopBits = StopBits.One
SerialPort.Handshake = Handshake.None
SerialPort.Open()
SerialPort.ReadTimeout = 200
If SerialPort.IsOpen Then
' TextBox1.Text = ""
End If
End Sub
Private Sub SerialPort_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived
dataIn = SerialPort.ReadExisting
dataIn = TextBox1.Text
TextBox1.Text += SerialPort.ReadExisting().ToString()
SetText(TextBox1.ToString())
End Sub
Delegate Sub SetTextCallback(ByVal text As String)
Private Sub SetText(ByVal text As String)
If Me.TextBox1.InvokeRequired Then
Dim d As SetTextCallback = New SetTextCallback(AddressOf SetText)
Me.Invoke(d, New Object() {text})
Else
Me.TextBox1.Text = text.ToString
End If
End Sub
解决方案
您不能设置所有这些属性并使用没有SerialPort
.
我不熟悉串口代码,但我怀疑事件中sender
的DataReceived
是串口。所以只需投射sender
到SerialPort
. 调用ReadExisting
返回字符串的方法并将其分配.Text
给TextBox
.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim sp As New SerialPort()
sp.PortName = "COM1"
sp.BaudRate = CInt("9600")
sp.Parity = Parity.None
sp.StopBits = StopBits.One
sp.Handshake = Handshake.None
sp.Open()
sp.ReadTimeout = 200
End Sub
Private Sub SerialPort_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived
TextBox1.Text += DirectCast(sender, SerialPort).ReadExisting
End Sub
您还需要在某个地方处理端口。