Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在VB.net中用代码创建串行端口_Vb.net_Visual Studio_Serial Port - Fatal编程技术网

在VB.net中用代码创建串行端口

在VB.net中用代码创建串行端口,vb.net,visual-studio,serial-port,Vb.net,Visual Studio,Serial Port,我正在尝试仅使用代码在VB.net中创建串行端口。因为我正在创建类库,所以无法使用内置组件。我尝试过实例化一个新的SeialPort()对象,但这似乎还不够。我肯定有一些简单的东西我错过了,任何帮助将不胜感激!谢谢 另外,我应该补充一点,我现在遇到的问题是获取处理datareceived事件的代码。除此之外,它可能会工作,但由于这个问题,我无法判断。我在过去的一个项目中使用了SerialPort.Net类,我工作得很好。你真的不需要别的了。检查控制面板中的硬件设置,并确保使用相同的参数实例化该类

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


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

我在过去的一个项目中使用了SerialPort.Net类,我工作得很好。你真的不需要别的了。检查控制面板中的硬件设置,并确保使用相同的参数实例化该类。

我发现非常好

我从中编写的代码是:

port = new System.IO.Ports.SerialPort(name, 4800, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived);
port.Open();

void port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
    buffer = port.ReadLine();
    // process line
}
对不起,是C#但是


我唯一的问题是,如果端口在打开时被丢弃,则应用程序在退出时似乎会失败。

如果要使用事件,请确保使用“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

感谢大家的帮助,特别是关于使用WithEvents关键字实例化类的答案

我发现了一篇非常好的文章,解释了如何为串行端口创建管理器类。它还讨论了向串行端口发送二进制和十六进制数据。这很有帮助