How to Get IP Addresses in LAN Network Using VB.Net - vb.net

enter image description hereI want to get IP addresses in That are connected with LAN network. I seen a youtube tutorial Youtube Video Got the addresses but only last address show here in my dataGridView
I want to get all addresses in datagridviewlist using VB.Net
Maybe my english is bit lower but I need help
This is My Code
Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Net.Sockets
Imports System.Threading
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim strHost As String
Dim strIp As String
strHost = Dns.GetHostName()
strIp = Dns.GetHostByName(strHost).AddressList(0).ToString()
TxtForIp.Text = strIp
End Sub
Private Sub BgScanningForIps_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BgScanningForIps.DoWork
Dim ping As Ping
Dim addr As IPAddress
Dim pinRpl As PingReply
Dim host As IPHostEntry
Dim name As String
Thread.Sleep(500)
Parallel.For(0, 254, Sub(i, loopState)
ping = New Ping()
pinRpl = ping.Send(TxtForIp.Text + i.ToString())
Me.BeginInvoke(CType(Sub()
If pinRpl.Status = IPStatus.Success Then
Try
addr = IPAddress.Parse(TxtForIp.Text + i.ToString())
host = Dns.GetHostEntry(addr)
name = host.HostName
DataGridView1.Rows.Add()
Dim nRowIndex As Integer = DataGridView1.Rows.Count - 1
DataGridView1.Rows(nRowIndex).Cells(0).Value = TxtForIp.Text + i.ToString()
DataGridView1.Rows(nRowIndex).Cells(1).Value = name
DataGridView1.Rows(nRowIndex).Cells(2).Value = "active"
Catch ex As Exception
name = "?"
End Try
End If
End Sub, Action))
End Sub)
MessageBox.Show("Scanned")
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BgScanningForIps.RunWorkerAsync()
End Sub
End Class

Related

Counting files in a directory not working

I am trying to count the number of files in a directory and hide a number of buttons corresponding to the total amount of buttons take away the number of files in the directory. At the moment the code appears to not run past the line where it creates the directory, there are no errors but the text doesn't update nor does the button hide.
Option Explicit On
Imports System.IO
Imports System.Net.Sockets
Public Class Form2
Dim username As String
Dim FriendsArray() As String
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim i As Integer
i = 0
Form1.Hide()
username = File.ReadAllText("C:\Program Files\PolarisChatUser\TempUser\UserID.txt")
Directory.CreateDirectory("C:\Program Files\PolarisChatUser\" + username + "\Friends")
For Each foundFile As String In My.Computer.FileSystem.GetFiles("C:\Program Files\PolarisChatUser\" + username + "\Friends")
FriendsArray(i) = foundFile
i = i + 1
Next
btnF1.Text = FriendsArray.Length
If FriendsArray.Length = 0 Then
btnF1.Hide()
End If
End Sub
End Class
updated code
Option Explicit On
Imports System.IO
Imports System.Net.Sockets
Public Class Form2
Dim username As String
Dim FriendsArray As List(Of String)
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim i As Integer
i = 0
Form1.Hide()
username = File.ReadAllText("C:\Program Files\PolarisChatUser\TempUser\UserID.txt")
Directory.CreateDirectory("C:\Program Files\PolarisChatUser\" + username + "\Friends")
For Each foundFile As String In My.Computer.FileSystem.GetFiles("C:\Program Files\PolarisChatUser\" + username + "\Friends")
FriendsArray.Add(foundFile)
i = i + 1
Next
btnF1.Text = FriendsArray.Count
If FriendsArray.Count = 1 Then
btnF1.Hide()
End If
End Sub
End Class
Directory.GetFiles returns an array of file names in the directory. Simply get the .Count or .Length property of the array.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim TheFiles = Directory.GetFiles("C:\Users\maryo\Desktop")
Dim NumberOfFilesInDirectory As Integer = TheFiles.Count
Debug.Print(NumberOfFilesInDirectory.ToString)
End Sub
Try like this.
Dim counter As Integer = Directory.GetFiles(FolderPath, "*.*", SearchOption.AllDirectories).Length;
MsgBox("Number of files is : " + counter)
or Specific File Default
FilesInFolder = Directory.GetFiles(FolderPath, "*.Doc").Count
MsgBox("Number of files is : " + FilesInFolder )

Get IP Addresses of 6 devices using MAC addresses using VB.NET

How do I modify my code to populate a listbox of IP addresses if I know 6 devices MAC addresses?
I am using VB.net to show me my current IP and MAC address but I want to change it to add to a ListBox to show 6 devices on the same network using their MAC addresses. Since we cannot modify the DHCP server, we just want a simple way to show each device's IP address using their known Mac addresses. I will add the MAC addresses in code. but Just want to have the listbox populate on startup of the app.
Existing Code:
Imports System.Net
Imports System.Runtime.InteropServices
Imports System.ComponentModel
Imports System.IO
Imports System.Net.NetworkInformation
Public Class Form1
Private Sub Form1_MouseClick(sender As Object, e As MouseEventArgs) Handles Me.MouseClick
Dim mac As String
mac = GetMacAddress()
Label1.Text = mac
End Sub
Function GetMacAddress()
Dim nics() As NetworkInterface = NetworkInterface.GetAllNetworkInterfaces()
Return nics(0).GetPhysicalAddress.ToString
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.Close()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
GetIPv4Address()
End Sub
Private Function GetIPv4Address() As String
GetIPv4Address = String.Empty
Dim strHostName As String = System.Net.Dns.GetHostName()
Dim iphe As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry(strHostName)
For Each ipheal As System.Net.IPAddress In iphe.AddressList
If ipheal.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork Then
GetIPv4Address = ipheal.ToString()
Label2.Text = "IP Address: " & ipheal.ToString
End If
Next
End Function
End Class
Thanks in advance!
Updated Answer - After some more digging, I found untweaked version of the code below here and tweaked it a bit.
What you end up with is a list of IpInfo structures. Each of these objects has the self-explanatory properties of IpAddress, MacAddress and HostName. You can iterate through the list and IP addresses the matching mac addresses to your listbox.
You may need to tweak the Thread.Sleep interval to make sure that you get all the results, but I hope this new answer sorts you out.
If it does, I would suggest removing the comments about the code not working so that they don't confuse others looking at this answer.
Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Net.Sockets
Public Class Form1
Structure IpInfo
Dim IpAddress As String
Dim HostName As String
Dim MacAddress As String
End Structure
Dim connectedIPAddresses As New List(Of IpInfo)
Private Shared Function NetworkGateway() As String
Dim ip As String = Nothing
For Each f As NetworkInterface In NetworkInterface.GetAllNetworkInterfaces()
If f.OperationalStatus = OperationalStatus.Up Then
For Each d As GatewayIPAddressInformation In f.GetIPProperties().GatewayAddresses
ip = d.Address.ToString()
Next
End If
Next
Return ip
End Function
Public Sub Ping_all()
Dim gate_ip As String = NetworkGateway()
Dim array As String() = gate_ip.Split("."c)
For i As Integer = 2 To 255
Dim ping_var As String = array(0) & "." & array(1) & "." & array(2) & "." & i.ToString
Ping(ping_var, 1, 1000)
Next
Task.WhenAll(taskList)
End Sub
Dim taskList As New List(Of Task)
Public Sub Ping(ByVal host As String, ByVal attempts As Integer, ByVal timeout As Integer)
For i As Integer = 0 To attempts - 1
taskList.Add(Task.Run(Sub()
Try
Dim ping As System.Net.NetworkInformation.Ping = New System.Net.NetworkInformation.Ping()
AddHandler ping.PingCompleted, AddressOf PingCompleted
ping.SendAsync(host, timeout, host)
Catch
End Try
End Sub))
Next
End Sub
Private Sub PingCompleted(ByVal sender As Object, ByVal e As PingCompletedEventArgs)
Dim ip As String = CStr(e.UserState)
If e.Reply IsNot Nothing AndAlso e.Reply.Status = IPStatus.Success Then
Dim hostname As String = GetHostName(ip)
Dim macaddres As String = GetMacAddress(ip)
Dim newIpAddress As IpInfo
newIpAddress.IpAddress = ip
newIpAddress.MacAddress = macaddres
newIpAddress.HostName = hostname
connectedIPAddresses.Add(newIpAddress)
Else
End If
End Sub
Public Function GetHostName(ByVal ipAddress As String) As String
Try
Dim entry As IPHostEntry = Dns.GetHostEntry(ipAddress)
If entry IsNot Nothing Then
Return entry.HostName
End If
Catch __unusedSocketException1__ As SocketException
End Try
Return Nothing
End Function
Public Function GetMacAddress(ByVal ipAddress As String) As String
Dim macAddress As String = String.Empty
Dim Process As System.Diagnostics.Process = New System.Diagnostics.Process()
Process.StartInfo.FileName = "arp"
Process.StartInfo.Arguments = "-a " & ipAddress
Process.StartInfo.UseShellExecute = False
Process.StartInfo.RedirectStandardOutput = True
Process.StartInfo.CreateNoWindow = True
Process.Start()
Dim strOutput As String = Process.StandardOutput.ReadToEnd()
Dim substrings As String() = strOutput.Split("-"c)
If substrings.Length >= 8 Then
macAddress = substrings(3).Substring(Math.Max(0, substrings(3).Length - 2)) & "-" & substrings(4) & "-" & substrings(5) & "-" & substrings(6) & "-" & substrings(7) & "-" + substrings(8).Substring(0, 2)
Return macAddress
Else
Return "OWN Machine"
End If
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Ping_all()
Threading.Thread.Sleep(10000)
For Each ip As IpInfo In connectedIPAddresses
ListBox1.Items.Add(ip.IpAddress)
Next
End Sub

SendKey to a game in VB.net

Quick question, I have a WinForm vb.net project that sends keystroke using the SendKey method based on a received UDP message. My code works like charm when using Notepad or something like that but, the ultimate goal of my app is to send those commands to a game (Elite Dangerous in this case) but it does not work... The game never receives the keystroke.
Any idea why? The game is the focused application because I'm playing it, if I switch to my app I see the UDP message is received and the command is sent, if I focus Notepad, it works but not with the game :(
Here is my code:
Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Imports System.ComponentModel
Public Class Form1
Private Shared listenPort As Integer
Private Shared HostIP As IPAddress
Public CheckResult As Boolean = False
Public KeystrokeMessage As String = ""
Public cpt As Integer = 0
Dim p() As Process
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Disable the Start button until a local IP is selected
StartStopBtn.Enabled = False
' ####################################
' ## Get list of local IP addresses ##
' ####################################
Dim hostname As String
'get host name
hostname = System.Net.Dns.GetHostName()
'get a list of IP addresses for the give host name
Dim hostentry As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry(hostname)
'List all IP used on the PC in the ComboBox
For Each ip As System.Net.IPAddress In hostentry.AddressList
If ip.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork Then
ComboBox1.Items.Add(ip.ToString())
End If
Next
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
' If an IP address is selected, the Start button is enabled
If ComboBox1.SelectedItem <> "- Please select -" Then
StartStopBtn.Enabled = True
End If
End Sub
Private Sub StartStopBtn_Click(sender As Object, e As EventArgs) Handles StartStopBtn.Click
Select Case StartStopBtn.Text
Case "Start Listening"
' Update the interface
StartStopBtn.Text = "Stop Listening"
ComboBox1.Enabled = False
UDPTextBox.Enabled = False
' Start listening to UDP messages
listenPort = CInt(UDPTextBox.Text)
If Not (ComboBox1.SelectedItem = "Any") Then
Try
HostIP = IPAddress.Parse(ComboBox1.SelectedItem)
Catch ex As Exception
MsgBox("error")
End Try
End If
If Not BackgroundWorker1.IsBusy = True Then
BackgroundWorker1.RunWorkerAsync()
End If
Case "Stop Listening"
' Update the interface
StartStopBtn.Text = "Start Listening"
ComboBox1.Enabled = True
UDPTextBox.Enabled = True
' Stop listening to UDP messages
BackgroundWorker1.CancelAsync()
BackgroundWorker1.CancelAsync()
End Select
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
Dim done As Boolean = False
Dim listener As New UdpClient(listenPort)
Dim groupEP As New IPEndPoint(HostIP, listenPort)
Dim mystring As String
Try
While Not done
If BackgroundWorker1.CancellationPending = True Then
e.Cancel = True
listener.Close()
Exit While
Else
If (listener.Available > 0) Then
Dim bytes As Byte() = listener.Receive(groupEP)
KeystrokeMessage = Encoding.ASCII.GetString(bytes, 0, bytes.Length)
mystring = "From " & groupEP.ToString() & " : " & KeystrokeMessage
worker.ReportProgress(0, mystring)
End If
End If
End While
Catch ex As Exception
Finally
listener.Close()
End Try
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
If (BackgroundWorker1.CancellationPending = False) Then
MessageTextBox.Text = (e.UserState.ToString)
SendKeystroke()
End If
Update()
End Sub
Private Sub SendKeystroke()
' Check the content of the received UDP message
Select Case KeystrokeMessage.Substring(0, 8)
' If the message starts by "SendKey." then remote the header and send the rest of the message
' ex: if the message is "SendKey.A" the process will send A
Case "SendKey."
SendKeys.SendWait(KeystrokeMessage.Substring(8))
' If not, just display the message in the Textbox with the mention "Invalid command" and do nothing else
Case Else
MessageTextBox.Text = MessageTextBox.Text & " (Invalid command!)"
End Select
End Sub
End Class
Thanks a lot :)

VB LAN Messenger having issues

I have made a small LAN messenger and I tried it with two pc's and it didnt work however running two of the applications with one listening to port 40004 and writing to 40005 and one listening to 40005 and writing to 40004 works.
The problem seems to be in the sendb_click where I send the message. It says Receipent not connected.
Error message:
System.net.sockets.socketexception (0x80004005); No connection could be made
because the target machine actively refused it 127.0.0.1:40003
at system.net.sockets.tcpclient..ctor(string hostname,int32 port)
at messenger.form2.sendb_click(object sender, eventargs e) in
D:\Messenger\Messenger\Form2.vb:line 97
:Interface
When connected you can choose a computer that is connected to the network on the right and message it. Im planning on having generated ports or whatever but for testing ive just made 40004 and 40005 the ports.
What is going wrong? Do i have to port forward or something?
below is my code
Imports System.Net.Sockets
Imports System.Threading
Imports System.IO
Imports System.Net.Dns
Imports System.DirectoryServices
Public Class Form2
Class entity
Public name As String
Public ip As String
Public port As Integer
End Class
Public reciepent As New entity
Public user As New entity
Public CLient As New TcpClient
Public listener As New TcpListener(40003)
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
usernametb.Text = user.name
FindingThreats()
getmyip()
ipl.Text = user.ip
user.port = 40003
portl.Text = user.port
' listener = New TcpListener(40004)
Dim ListThread As New Thread(New ThreadStart(AddressOf Listening))
ListThread.Start()
End Sub
Private Sub Listening()
listener.Start()
End Sub
Sub FindingThreats()
UsersL.Items.Clear()
Dim childEntry As DirectoryEntry
Dim ParentEntry As New DirectoryEntry
Try
ParentEntry.Path = "WinNT:"
For Each childEntry In ParentEntry.Children
Select Case childEntry.SchemaClassName
Case "Domain"
Dim SubChildEntry As DirectoryEntry
Dim SubParentEntry As New DirectoryEntry
SubParentEntry.Path = "WinNT://" & childEntry.Name
For Each SubChildEntry In SubParentEntry.Children
Select Case SubChildEntry.SchemaClassName
Case "Computer"
UsersL.Items.Add(SubChildEntry.Name)
End Select
Next
End Select
Next
Catch Excep As Exception
MsgBox("Error While Reading Directories : " + Excep.Message.ToString)
Finally
ParentEntry = Nothing
End Try
End Sub
Sub getmyip()
For Each ip As Net.IPAddress In
GetHostEntry(GetHostName).AddressList
user.ip = ip.ToString
Next
End Sub
Sub getip(strhostname As String, returnip As String)
Try
returnip = GetHostByName(strhostname).AddressList(0).ToString()
reciepent.ip = returnip
Catch
MsgBox("This user is Offline.")
End Try
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles UsersL.SelectedIndexChanged
CUL.Items.Clear()
CUL.Items.Add("Connected Users:")
Dim ip As String
Dim hostname = UsersL.SelectedItem.ToString
getip(hostname, ip)
reciepent.port = 40004
Timer1.Enabled = True
CUL.Items.Add(user.name)
End Sub
Private Sub Label2_Click(sender As Object, e As EventArgs) Handles Label2.Click
Me.Close()
End Sub
Private Sub SendB_Click(sender As Object, e As EventArgs) Handles SendB.Click
Try
CLient = New TcpClient("127.0.0.1", 40004) 'reciepent.port)
Dim Writer As New StreamWriter(CLient.GetStream())
Writer.Write(ChatB.Text)
ChatL.Items.Add("> " & ChatB.Text)
Writer.Flush()
Catch
MsgBox("Receipent not connected.")
End Try
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim message As String
If listener.Pending = True Then
message = ""
CLient = listener.AcceptTcpClient()
Dim Reader As New StreamReader(CLient.GetStream())
While Reader.Peek > -1
message = message + Convert.ToChar(Reader.Read()).ToString
End While
ChatL.Items.Add("< " & message)
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
FindingThreats()
End Sub
Private Sub Form2_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
listener.Stop()
Me.Close()
End Sub
End Class

Ccalling receive data function on Vb

I have gone through the Link vb serial communication. They ar eusing below function for getting data. My question are as follows
How to call this below function on VB
My data from serial are CSV value how to separate and display in a text box
Updating the text box values?
Function ReceiveSerialData() As String
' Receive strings from a serial port.
Dim returnStr As String = ""
Dim com3 As IO.Ports.SerialPort = Nothing
Try
com3 = My.Computer.Ports.OpenSerialPort("COM3")
com3.ReadTimeout = 10000
Do
Dim Incoming As String = com3.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 com3 IsNot Nothing Then com3.Close()
End Try
Return returnStr
End Function
MY compelte code aS BELOW
Imports System
Imports System.IO.Ports
Imports System.ComponentModel
Imports System.Threading
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Windows.Forms
Imports Microsoft.VisualBasic.FileIO
Imports System.IO
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim myPort As Array
myPort = IO.Ports.SerialPort.GetPortNames()
PortComboBox.Items.AddRange(CType(myPort, Object()))
BaudComboBox.Items.Add(9600)
BaudComboBox.Items.Add(19200)
BaudComboBox.Items.Add(38400)
BaudComboBox.Items.Add(57600)
BaudComboBox.Items.Add(115200)
ConnectButton.Enabled = True
DisconnectButton.Enabled = False
Timer1.Interval = 1000
Timer1.Start()
Receive.Text = ReceiveSerialData()
End Sub
Private Sub ConnectButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConnectButton.Click
SerialPort1.PortName = PortComboBox.Text
SerialPort1.BaudRate = CInt(BaudComboBox.Text)
SerialPort1.Open()
Timer1.Start()
'lblMessage.Text = PortComboBox.Text & " Connected."
ConnectButton.Enabled = False
DisconnectButton.Enabled = True
End Sub
Private Sub DisconnectButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DisconnectButton.Click
SerialPort1.Close()
DisconnectButton.Enabled = False
ConnectButton.Enabled = True
End Sub
Function ReceiveSerialData() As String
' Receive strings from a serial port.
Dim returnStr As String = ""
Dim com3 As IO.Ports.SerialPort = Nothing
Try
com3 = My.Computer.Ports.OpenSerialPort("COM3")
com3.ReadTimeout = 10000
Do
Dim Incoming As String = com3.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 com3 IsNot Nothing Then com3.Close()
End Try
Return returnStr
End Function
End Class
i am trying to create a short sample for you but you need to understand threading and serial working for this. follow the steps to create this sample
add new class module to your code with name mySerial and past following code in it (replace code)
Imports System.Threading
Imports System.IO.Ports
Imports System.ComponentModel
Public Class dataReceivedEventArgs
Inherits EventArgs
Private m_StringData As String
Public Sub New(strData As String)
Me.m_StringData = strData
End Sub
Public ReadOnly Property ReceivedData As String
Get
Return m_StringData
End Get
End Property
End Class
Public Class mySerial
Private ReadThread As Thread
Dim SPort As SerialPort
Private syncContext As SynchronizationContext
Public Event DataReceived(Sender As Object, ByVal e As dataReceivedEventArgs)
Public Sub New(ByVal COMMPORT As String, ByVal BaudRate As Integer)
Me.New(COMMPORT, BaudRate, Parity.None, 8, StopBits.One)
End Sub
Public Sub New(ByVal _COMMPORT As String, ByVal _BaudRate As Integer, ByVal _Parity As Parity, ByVal _DataBits As Integer, ByVal _StopBits As StopBits)
SPort = New SerialPort
With SPort
.PortName = _COMMPORT
.BaudRate = _BaudRate
.Parity = _Parity
.DataBits = _DataBits
.StopBits = _StopBits
.Handshake = Handshake.XOnXOff
.DtrEnable = True
.RtsEnable = True
.NewLine = vbCrLf
End With
Me.syncContext = AsyncOperationManager.SynchronizationContext
ReadThread = New Thread(AddressOf ReadPort)
End Sub
Public Sub OpenPort()
If Not SPort.IsOpen Then
SPort.Open()
SPort.DiscardNull = True
SPort.Encoding = System.Text.Encoding.ASCII
ReadThread.Start()
End If
End Sub
Public Sub ClosePort()
If SPort.IsOpen Then
SPort.Close()
End If
End Sub
Private Sub ReadPort()
Do While SPort.IsOpen
Dim ReceviceData As String = String.Empty
Do While SPort.BytesToRead <> 0 And SPort.IsOpen And ReceviceData.Length < 5000
Try
ReceviceData &= SPort.ReadExisting()
Thread.Sleep(100)
Catch ex As Exception
End Try
Loop
If ReceviceData <> String.Empty Then
'raise event and provide data
syncContext.Post(New SendOrPostCallback(AddressOf onDataReceived), ReceviceData)
End If
Thread.Sleep(500)
Loop
End Sub
Private Sub onDataReceived(ByVal ReceivedData As String)
RaiseEvent DataReceived(Me, New dataReceivedEventArgs(ReceivedData))
End Sub
End Class
this is class which will work as wrapper class for you, now to make it work add a form with name frmSerial and a textBox with name txtData and set multiline=true, scrollbars=both, now past following code in it
Public Class frmSerial
Dim WithEvents _Serial As mySerial
Private Sub frmSerial_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
_Serial.ClosePort()
End Sub
Private Sub frmSerial_Shown(sender As Object, e As EventArgs) Handles Me.Shown
_Serial = New mySerial("COM1", 9600)
_Serial.OpenPort()
End Sub
Private Sub _Serial_DataReceived(Sender As Object, e As dataReceivedEventArgs) Handles _Serial.DataReceived
txtData.Text &= e.ReceivedData
txtData.SelectionStart = txtData.Text.Length
txtData.ScrollToCaret()
End Sub
End Class
hop this helps you and people like you