[2008] SerialPort DataRCV Handler
I have a SerialPort DataReceived Handler that I am fond of. So I thought why not move it to it's own Module and re-use it.
Well, that didn't work out well, even though I got it to work.
So how would you go about having a generic SerialPort DataReceived Handler?
(I have been copy / pasting the code)
Re: [2008] SerialPort DataRCV Handler
Something like this maybe?
vb.net Code:
Public Class SerialPortDataReceiver
Private comPort As System.IO.Ports.SerialPort = Nothing
Private _DisplayControl As Control = Nothing
Public Sub New(ByVal serialPort As System.IO.Ports.SerialPort)
Me.comPort = serialPort
AddHandler Me.comPort.DataReceived, AddressOf SerialPortDataReceived
Me.OpenPort()
End Sub
Public Sub New(ByVal serialPort As System.IO.Ports.SerialPort, ByVal displayControl As Control)
Me.comPort = serialPort
AddHandler Me.comPort.DataReceived, AddressOf SerialPortDataReceived
Me._DisplayControl = displayControl
Me.OpenPort()
End Sub
Public Property DisplayControl() As Control
Get
Return Me._DisplayControl
End Get
Set(ByVal value As Control)
Me._DisplayControl = value
End Set
End Property
Public ReadOnly Property SerialPort() As System.IO.Ports.SerialPort
Get
Return Me.comPort
End Get
End Property
Private Sub SerialPortDataReceived(ByVal sender As Object, _
ByVal e As System.IO.Ports.SerialDataReceivedEventArgs)
If Me._DisplayControl IsNot Nothing Then
Me._DisplayControl.Invoke(New myDelegate(AddressOf UpdateDisplayControlText), New Object() {})
End If
End Sub
Private Delegate Sub myDelegate()
Private Sub UpdateDisplayControlText()
Dim intBytesAvailable As Integer = comPort.BytesToRead
If intBytesAvailable > 0 Then
Me._DisplayControl.Text = comPort.ReadExisting()
End If
End Sub
Public Sub SendCommand(ByVal command As String)
If Me.comPort.IsOpen() Then
Me.comPort.Write(command)
Else
MessageBox.Show(Me.comPort.PortName & " is closed!")
End If
End Sub
Private Sub OpenPort()
If Not Me.comPort.IsOpen Then
Try
Me.comPort.Open()
Catch ex As Exception
Throw New IO.IOException("Can not open serial port " & Me.comPort.PortName, ex)
End Try
End If
End Sub
End Class