在 VB.net 中的代码中创建串行端口 [英] Creating a Serial Port in code in VB.net

查看:18
本文介绍了在 VB.net 中的代码中创建串行端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试仅使用代码在 VB.net 中创建串行端口.因为我正在创建一个类库,所以我不能使用内置组件.我已经尝试实例化一个新的 SeialPort() 对象,但这似乎还不够.我确信我缺少一些简单的东西,任何帮助将不胜感激!谢谢!

I am trying to create a serial port in VB.net using code only. Because I am creating a class library I cannot use the built-in component. I have tried instantiating a new SeialPort() object, but that does not seem to be enough. I'm sure there is something simple I am missing and any help would be greatly appreciated! Thanks!

附:我应该补充一点,我现在遇到的问题是获取代码来处理 datareceived 事件.除此之外它可能正在工作,但由于这个问题我无法判断.

P.S. I should add that the problem I am having at this time is getting the code to handle the datareceived event. Other than that it might be working, but I can't tell because of that problem.

推荐答案

如果您想使用事件,请确保使用withevents"声明您的 serialPort 对象.下面的示例将允许您连接到串行端口,并将使用接收到的字符串引发事件.

If you want to use the events make sure you declare your serialPort object using the 'withevents'. The below example will allow you to connect to a serial port, and will raise an event with the received string.

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

这篇关于在 VB.net 中的代码中创建串行端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆