开发者

Can I make an array of serial ports in vb?

I'm fairly new to Visual Basic (VB), but I've already got running code to access all my serial port. The problem is I want to load multiple serial ports into an array and loop through them in my funct开发者_如何学Cions. The program allows me to create ports(), but fails when I try to populate it.

Dim ports As IO.Ports.SerialPorts()
ports(0) = SerialPort1

Where SerialPort1 is an object I draged from the Visual Studio toolbox.


I would use List(of) for this:

    Dim Ports As New List(Of IO.Ports.SerialPort)

    Dim newport1 As New IO.Ports.SerialPort
    newport1.PortName = "COM1"

    Dim newport2 As New IO.Ports.SerialPort
    newport2.PortName = "COM2"

    Ports.Add(newport1)
    Ports.Add(newport2)

    'later in code, handle all ports with index in the Ports-list
    Ports(0).Open() 'open port1
    Ports(1).Open() 'open port2

or this slightly different way:

    Dim Ports As New List(Of IO.Ports.SerialPort)

    Ports.Add(New IO.Ports.SerialPort)
    Ports.Add(New IO.Ports.SerialPort)

    'later in code, handle all ports with index in the Ports-list
    Ports(0).PortName = "COM1"
    Ports(0).Open()

    Ports(1).PortName = "COM2"
    Ports(1).Open()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜