I started learning about TCP/Sockets yesterday and decided to make a chatbox for a friend and I.
Unfortunately, i am having some difficulties with MultiThreading.
Whenever i am using it, i can no longer receive messages from my friend.
But, if i disable it then, everything works perfectly.
I don't know what's going on here, could somebody help?
Imports System.Net.Sockets
Imports System.Net
Public Class ServerClient
Dim _TCPServer As Socket
Dim _TCPListener As TcpListener
Dim _ListenerThread As System.Threading.Thread
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
'When Submit is pressed, send some text to the client
Dim bytes() As Byte = System.Text.Encoding.ASCII.GetBytes(txtInput.Text)
txtBox.AppendText(vbCrLf & "Server: " & txtInput.Text)
txtInput.Clear()
_TCPServer.Send(bytes)
End Sub
Private Sub TCPListen()
'If somebody calls port 2424, accept it, unblock the socket and start the timer
_TCPListener = New TcpListener(IPAddress.Any, 2424)
_TCPListener.Start()
_TCPServer = _TCPListener.AcceptSocket()
btnSend.Enabled = True
txtBox.AppendText("Connection Established" & vbCrLf)
_TCPServer.Blocking = False
_Timer.Enabled = True
End Sub
Private Sub _Timer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _Timer.Tick
'If data has been sent, receive it
Try
Dim rcvdbytes(_TCPServer.ReceiveBufferSize) As Byte
_TCPServer.Receive(rcvdbytes)
txtBox.AppendText(vbCrLf & "Client: " & System.Text.Encoding.ASCII.GetString(rcvdbytes) & vbCrLf)
Catch ex As Exception
End Try
End Sub
Private Sub ServerClient_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Link the new thread to TCPListen(), allow access to all threads and wait for a call
_ListenerThread = New Threading.Thread(AddressOf TCPListen)
Control.CheckForIllegalCrossThreadCalls = False
txtBox.AppendText("Waiting for connection.." & vbCrLf)
btnSend.Enabled = False
_ListenerThread.Start()
End Sub
End Class
This example project contains four classes - TcpCommServer, TcpCommClient, clsAsyncUnbuffWriter and CpuMonitor. With these classes, you will not only be able to instantly add TCP/IP functionality to your VB.NET applications, but also has most of the bells and whistles we're all looking for. With these classes, you will be able to connect multiple clients to the server on the same port. You will be able to easily: throttle bandwidth to the clients, and send and receive files and data (text?) along 250 provided channels simultaneously on a single connection.
http://www.codeproject.com/Articles/307315/Reusable-multithreaded-tcp-client-and-server-class
Well, i learned BackgroundWorkers could do the exact same thing and now it all works.
Private Sub ServerClient_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Wait for a call
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
TCPListen()
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
_Timer.Enabled = True
End Sub
Related
I am new to using Visual Basic and just have started coding using the language.
From simple coding, I want to try something a bit complex such as sending and receiving data through a serial port communication. I was able to go through a lot of tutorials about it and came about trying this code:
Imports System
Imports System.Threading
Imports System.IO.Ports
Imports System.ComponentModel
Public Class Form1
Dim myPort As Array
Delegate Sub SetTextCallback(ByVal [text] As String) 'Added to prevent threading errors during receiving of data
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myPort = IO.Ports.SerialPort.GetPortNames()
ComboBox1.Items.AddRange(myPort)
Button2.Enabled = False
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SerialPort1.PortName = ComboBox1.Text
SerialPort1.BaudRate = ComboBox2.Text
SerialPort1.Open()
Button1.Enabled = False
Button2.Enabled = True
Button3.Enabled = True
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
SerialPort1.Write(RichTextBox1.Text & vbCr) 'concatenate with \n
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
SerialPort1.Close()
Button1.Enabled = True
Button2.Enabled = False
Button3.Enabled = False
End Sub
Private Sub ReceivedText(ByVal [text] As String) 'input from ReadExisting
If Me.RichTextBox2.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
Me.RichTextBox2.Text &= [text] 'append text
End If
End Sub
Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
ReceivedText(SerialPort1.ReadExisting())
End Sub
End Class
Button1 is designated for Opening the Port while Button2 and Button3 are used to Write and Close the port respectively. The RichTextBox1 is where I can write the data I want to send and the RichTextBox2 is where the data received is displayed. Now my problem is whenever I click the button to Write data on the port nothing displays. I want to ask help on how to get about with this.
You can't write a message and read it on the same end of the serial communication.
If you want to "fake" the serial communication, so that your pc talks to itself, you have 2 solutions:
Use some nullmodem emulator to virtually create COM ports pairs that are connected through software. Software like com0com, does just what you are looking for, but sometimes is a bit tricky makings thingks work well at the start.
Another solution is to have 2 serial ports in your pc (with an usb
adapter for example) and connect the TRx pin of the sending port to the RDx pin
of the reading port, and the RDx pin of the sending port to the TRx pin
of the reading port. All other pins just 1 to 1. Then you can also read from write from one port and read from the other.
Both approaches do the same, the first through software, the second physically.
Here you have another SO question about that, where you can get more info. Also google "faking Serial ports" should help.
Is there any way to send text throught PC's without a client and a server program? Just simply send text from a program to another.
Even though you don't want to use clients and servers, this is the easiest way to go.
The server is a server that runs in the command prompt, but runs in the background of your program. The server and client won't be visible in any way.
A simple answer with few lines of codes are TCP Communication. This uses the ip addresses of the both computers and establish a server/client connection.
Every communication needs something that hosts it, to achieve this you code the program to contain the following:
Imports System.IO
Imports System.Net.Sockets
Public Class Form1
Dim listener As New TcpListener(8000)
Dim Client As TcpClient
Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
listener.Stop()
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Timer1.Start()
listener.Start()
End Sub
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
Dim Data As String = ""
Dim nStart As Integer
Dim nLast As Integer
If listener.Pending = True Then
Client = listener.AcceptTcpClient()
Dim Reader As New StreamReader(Client.GetStream)
While Reader.Peek > -1
Data &= Convert.ToChar(Reader.Read()).ToString
End While
If Not Data = "" Then
msgbox("This is the data recieved: " & Data)
End If
End If
End Sub
End Class
This will open a "TCPListener" on the localhost port 8000. Whenever a client sends data to the listener, the text of the textbox Textbox1 to the data sent.
To send data to the server, use the following code:
Option Explicit On
Imports System.IO
Imports System.Net.Sockets
Public Class Form1
Dim Client As TcpClient
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Try
//Ip to the local or remote, forwarded server. 127.0.0.1 is localhost - the same machine.
Client = New TcpClient("127.0.0.1", 8000)
Dim Writer As New StreamWriter(Client.GetStream())
Writer.Write("Hello World!")
Writer.Flush()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
This will, when Button1 is pressed, try to send the data/string "Hello World!" to the server.
This could be combined into one by having the application set up as following:
Imports System.IO
Imports System.Net.Sockets
Public Class Form1
Dim listener As New TcpListener(8000)
Dim Client As TcpClient
Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
listener.Stop()
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Timer1.Start()
listener.Start()
End Sub
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
Dim Data As String = ""
Dim nStart As Integer
Dim nLast As Integer
If listener.Pending = True Then
Client = listener.AcceptTcpClient()
Dim Reader As New StreamReader(Client.GetStream)
While Reader.Peek > -1
Data &= Convert.ToChar(Reader.Read()).ToString
End While
If Not Data = "" Then
'Change the string
End If
TextBox1.Text = Data
End If
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Try
//This has to be the address to the remote
Client = New TcpClient("xx.xx.xx.xx", 8000)
Dim Writer As New StreamWriter(Client.GetStream())
Writer.Write(TextBox2.Text)
Writer.Flush()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
To extend this and make it useable in a real application, use a backgroundworker to simply make the server and client run on another thread.
If you don't want to use socket or pipes, i can only think of files, which is more pc to pc than program to program.
why does the FileSystemWatcher fire twice? Is there an easy way to fix it? Surely if I update or edit the text file it should only fire once?
this link here http://weblogs.asp.net/ashben/archive/2003/10/14/31773.aspx says
Events being raised twice - An event will be raised twice if an event handler (AddHander FSW.Created, AddressOf FSW_Created) is
explicitly specified. This is because, by default, the public events
automatically call the respective protected methods (OnChanged,
OnCreated, OnDeleted, OnRenamed). To correct this problem, simply
remove the explicit event handler (AddHandler ...).
What does "remove the explicit event handler" mean?
Imports System.IO
Public Class Form2
Private Sub FileSystemWatcher1_Changed(ByVal sender As System.Object, ByVal e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Changed
'this fires twice
MessageBox.Show("test")
End Sub
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
FileSystemWatcher1.Path = "C:\Users\c\Desktop\test\"
FileSystemWatcher1.NotifyFilter = NotifyFilters.LastAccess Or NotifyFilters.LastWrite Or NotifyFilters.FileName Or NotifyFilters.DirectoryName Or NotifyFilters.CreationTime
FileSystemWatcher1.IncludeSubdirectories = False
FileSystemWatcher1.Filter = "text.txt"
End Sub
End Class
Update:
I have come up with 2 solutions. One uses Threads, and the other doesn't. Take your pick :-).
Without threading:
Imports System.IO
Public Class Form1
Private Sub FileSystemWatcher1_Changed(ByVal sender As System.Object, ByVal e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Changed
Dim watcher As System.IO.FileSystemWatcher = sender
watcher.EnableRaisingEvents = False
'Do work here while new events are not being raised.
MessageBox.Show("Test")
watcher.EnableRaisingEvents = True 'Now we can begin watching for new events.
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
FileSystemWatcher1.Path = "C:\Users\c\Desktop\test"
FileSystemWatcher1.NotifyFilter = NotifyFilters.LastWrite
FileSystemWatcher1.IncludeSubdirectories = False
FileSystemWatcher1.Filter = "test.txt"
End Sub
Private Sub FileSystemWatcher_OnChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
End Sub
End Class
This solution (without threading), sets the watcher.EnableRaisingEvents to False. It is after this point where you would normally process whatever files are affected (or changed). It then sets the EnableRaisingEvents back to True after your work is done.
With threading:
Imports System.IO
Public Class Form1
Private Sub FileSystemWatcher1_Changed(ByVal sender As System.Object, ByVal e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Changed
FileSystemWatcher1.EnableRaisingEvents = False
Threading.Thread.Sleep(250)
FileSystemWatcher1.EnableRaisingEvents = True
MessageBox.Show("test")
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
FileSystemWatcher1.Path = "C:\Users\c\Desktop\test"
FileSystemWatcher1.NotifyFilter = NotifyFilters.LastWrite
FileSystemWatcher1.IncludeSubdirectories = False
FileSystemWatcher1.Filter = "test.txt"
End Sub
Private Sub FileSystemWatcher_OnChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
End Sub
End Class
This solution, although a bit hacky, does work. It disables checking for new changes/events for 250ms and then re-enables checking, based on the assumption that you won't been needing to check for a change every 250ms. I have tried almost everything that I could think of to get a real solution for you but this will work in the meantime.
Check e.ChangeType. I imagine you're getting two different notifications. Perhaps LastAccess and LastModified. In which case, that's the expected behavior.
Today i crashed in FileSystemWatcher and found this site. Suggested Thread.Sleep cannot completely eliminate problem. Tested with fast counter-integer. And is blocking UI. Most problematic is startup, it sliped trough at 5s. Then i set FileSystemWatcher1.EnableRaisingEvents = False immediately in TimerWatcherChanged.Tick and never enabled again... But surprisingly counter still catch up-to 4 events! I would like to share my solution, non-blocking, with adjustable Timer. Feedback is welcome.
Imports System.IO
Imports System.Diagnostics
Public Class Form1
Dim fileName As String
Dim Fsw_counter As Integer
WithEvents TimerWatcherChanged As New Windows.Forms.Timer
WithEvents TimerTest As New Windows.Forms.Timer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TimerWatcherChanged.Interval = 100
TimerTest.Interval = 100 : TimerTest.Start()
TextBox1.Text = "C:\Downloads\New Text Document.txt"
TextBox1.SelectionStart = TextBox1.Text.Length
WatcherSetup()
End Sub
Sub WatcherSetup()
fileName = TextBox1.Text
FileSystemWatcher1.IncludeSubdirectories = False
FileSystemWatcher1.Path = Path.GetDirectoryName(fileName)
FileSystemWatcher1.Filter = Path.GetFileName(fileName)
FileSystemWatcher1.NotifyFilter = NotifyFilters.LastWrite
FileSystemWatcher1.EnableRaisingEvents = True
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
WatcherSetup()
End Sub
Private Sub FileSystemWatcher1_Changed(sender As Object, e As FileSystemEventArgs) Handles FileSystemWatcher1.Changed
If TimerWatcherChanged.Enabled = False Then
TimerWatcherChanged.Enabled = True
Fsw_counter += 1
' ***** Your WATCH Code put here... *****
End If
End Sub
Private Sub TimerWatcherChanged_Tick(sender As Object, e As EventArgs) Handles TimerWatcherChanged.Tick
TimerWatcherChanged.Enabled = False
End Sub
Private Sub TimerTest_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles TimerTest.Tick
TextBox2.Text = "Changed: " & Fsw_counter
If TimerWatcherChanged.Enabled = True Then
TextBox2.BackColor = Color.Red
Else
TextBox2.BackColor = Color.LawnGreen
End If
End Sub
End Class
I'm writing a program for an internship and need some advice. I've done my research but have mostly returned fruitless... I need to loop the "buttonOneClick for one second iterations. The program will send a "P" character, wait one second, send a p, wait one second, etc... Also I need to write the information it receives to an excel spreadsheet. Any help/critiquing of existing code would be greatly appreciated.
Here's what I have:
Public Class Form2
Dim buttonOnePush As Boolean = False
Dim buttonTwoPush As Boolean = False
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' Send strings to a serial port.
Using com5 As IO.Ports.SerialPort =
My.Computer.Ports.OpenSerialPort("COM5")
com5.WriteLine("P")
End Using
End Sub
Function ReceiveSerialData() As String
' Receive strings from a serial port.
Dim returnStr As String = ""
Dim com5 As IO.Ports.SerialPort = Nothing
Try
com5 = My.Computer.Ports.OpenSerialPort("COM5")
com5.ReadTimeout = 10000
Do
Dim Incoming As String = com5.ReadLine()
If Incoming Is Nothing Then
Exit Do
Else
returnStr &= Incoming & vbCrLf
End If
Loop
Catch ex As TimeoutException
returnStr = "Error: Serial Port read timed out."
Finally
If com5 IsNot Nothing Then com5.Close()
End Try
Return returnStr
End Function
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
If IsNumeric(TextBox1.Text) AndAlso IsNumeric(TextBox2.Text) Then
TextBox1.Text = CDec(TextBox2.Text)
End If
End Sub
Private Sub TextBox6_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox6.TextChanged
If IsNumeric(TextBox6.Text) AndAlso IsNumeric(TextBox3.Text) Then
TextBox6.Text = CDec(TextBox3.Text)
End If
End Sub
Private Sub TextBox7_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox7.TextChanged
If IsNumeric(TextBox7.Text) AndAlso IsNumeric(TextBox4.Text) Then
TextBox7.Text = CDec(TextBox4.Text)
End If
End Sub
Private Sub TextBox8_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox8.TextChanged
If IsNumeric(TextBox8.Text) AndAlso IsNumeric(TextBox5.Text) Then
TextBox8.Text = CDec(TextBox5.Text)
End If
End Sub
Private Sub TextBox15_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox15.TextChanged
If IsNumeric(TextBox15.Text) AndAlso IsNumeric(TextBox16.Text) Then
TextBox15.Text = Hex(TextBox16.Text)
End If
End Sub
Private Sub TextBox14_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox14.TextChanged
If IsNumeric(TextBox14.Text) AndAlso IsNumeric(TextBox11.Text) Then
TextBox14.Text = Hex(TextBox11.Text)
End If
End Sub
Private Sub TextBox13_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox13.TextChanged
If IsNumeric(TextBox13.Text) AndAlso IsNumeric(TextBox10.Text) Then
TextBox13.Text = Hex(TextBox10.Text)
End If
End Sub
Private Sub TextBox12_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox12.TextChanged
If IsNumeric(TextBox12.Text) AndAlso IsNumeric(TextBox9.Text) Then
TextBox12.Text = Hex(TextBox9.Text)
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
buttonTwoPush = True
buttonOnePush = False
Me.Close()
Form1.Close()
End Sub
End Class
Use a Timer to issue that command at one second intervals. Drag a Timer over to your form from the toolbox, and double click on it to get a _Tick method.
Set the .Interval member of the timer in your form's constructor, and use the .Start and .Stop methods to control it.
For the Excel piece, you'll need to add a reference to the project for the Microsoft Excel 12.0 (or 14.0 if you have Excel 2010) Object Library. Find this under the COM tab of the Add Reference dialog which you get by right clicking on the project in the Solution Explorer. See this page for an exhaustive reference (scroll down to the bottom of the page for a quick example in VB.NET).
After searching around I am still having issues with reading data from a serial port in VB.Net/VS2010. I know the Serial Port works, I can write to the port fine but when reading from it, nothing happens. I have only been programming for the last 3 weeks so am still trying to get my head around it all.
The program must run to capture data from a door logger, I will then be outputting the data to a database (not yet implemented - I want to get this part sorted first).
I have tried using several terminal programs as well as another device which outputs data onto the serial line, with nothing displaying in the textbox tbxIn.
Any help would be greatly appreciated.
Code is below:
Imports System.IO.Ports
Imports System.IO.Ports.SerialPort
Public Class Form1
Dim comPort As IO.Ports.SerialPort = Nothing
Dim sComPort As String = ""
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
GetSerialPortNames()
End Sub
Sub GetSerialPortNames()
' Show all available COM ports.
For Each sp As String In My.Computer.Ports.SerialPortNames
lstPorts.Items.Add(sp)
Next
End Sub
Private Sub lstPorts_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstPorts.SelectedIndexChanged
sComPort = lstPorts.SelectedItem
Button1.Enabled = True
End Sub
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' Open the serial port using the OpenSerialPort method
Button1.Enabled = False
Button2.Enabled = True
Try
comPort = My.Computer.Ports.OpenSerialPort(sComPort, 9600, IO.Ports.Parity.None, 8, 1)
' comPort.DtrEnable = True
comPort.ReadTimeout = 500
Do
comPort.WriteLine("Go")
Dim sIncomming As String = comPort.ReadLine()
tbxIn.Text = sIncomming & vbCrLf
Loop
Catch ex As TimeoutException
tbxIn.Text &= "Error: Serial Port Read Timeout" & vbCrLf
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
comPort.Close()
Button1.Enabled = True
Button2.Enabled = False
End Sub
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
tbxIn.Text = e.ToString
End Sub
End Class
PRetty sure this will get you what you need. You DON't need the Serial1 component on the designer. Remove that and use this code:
Private comPort As IO.Ports.SerialPort = Nothing
Private sComPort As String = ""
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
GetSerialPortNames()
End Sub
Sub GetSerialPortNames()
' Show all available COM ports.
For Each sp As String In My.Computer.Ports.SerialPortNames
lstPorts.Items.Add(sp)
Next
End Sub
Private Sub lstPorts_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstPorts.SelectedIndexChanged
sComPort = lstPorts.SelectedItem
Button1.Enabled = True
End Sub
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' Open the serial port using the OpenSerialPort method
Button1.Enabled = False
Button2.Enabled = True
Try
comPort = My.Computer.Ports.OpenSerialPort(sComPort, 9600, IO.Ports.Parity.None, 8, 1)
' comPort.DtrEnable = True
'must add handler
AddHandler comPort.DataReceived, AddressOf SerialPort1_DataReceived
comPort.ReadTimeout = 500
Do
comPort.WriteLine("Go")
Dim sIncomming As String = comPort.ReadLine()
tbxIn.Text = sIncomming & vbCrLf
Loop
Catch ex As TimeoutException
tbxIn.Text &= "Error: Serial Port Read Timeout" & vbCrLf
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
comPort.Close()
'remove handler
RemoveHandler comPort.DataReceived, AddressOf SerialPort1_DataReceived
Button1.Enabled = True
Button2.Enabled = False
End Sub
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs)
tbxIn.Text = e.ToString
End Sub