Sunday, February 22, 2009

Reading and Writing a File in VB 2005

We occasionally need to read or write a file in Visual Basic 2005. For an easy reference, we want to post a few code here. The following two examples of reading and writing a file are from this web site.

Dim objStreamReader As StreamReader
Dim strLine As String

'Pass the file path and the file name to the StreamReader constructor.
objStreamReader = New StreamReader("C:\Boot.ini")

'Read the first line of text.
strLine = objStreamReader.ReadLine

'Continue to read until you reach the end of the file.
Do While Not strLine Is Nothing
  'Write the line to the Console window.
  Console.WriteLine(strLine)

  'Read the next line.
  strLine = objStreamReader.ReadLine
Loop

'Close the file.
objStreamReader.Close()

Dim objStreamWriter As StreamWriter

'Pass the file path and the file name to the StreamWriter constructor.
objStreamWriter = New StreamWriter("C:\Testfile.txt")

'Write a line of text.
objStreamWriter.WriteLine("Hello World")
'Write a second line of text.
objStreamWriter.WriteLine("From the StreamWriter class")

'Close the file.
objStreamWriter.Close()


If an error occurs while processing the file, the current method might be exited before you have an opportunity to close the file. A Try ... Finally block can be used to avoid this problem.

Dim strLine As String
Dim sr As StreamReader = Nothing
Try
    sr = New StreamReader(fileName)
    strLine = sr.ReadToEnd()
Finally
    sr.Close()
End Try



Visual Basic 2005 has a new Using statement that can automatically release one or more IDisposable objects. Any exception will be reported to callers. If you want to catch exceptions, you need a complete Try ... Catch ... Finally block.

Dim strLine As String
Using sr As New StreamReader(fileName)
    strLine = sr.ReadToEnd
End Using


Reading a text file can also be performed more easily by means of the new File.ReadAllText static method. For binary file, File.ReadAllBytes can be used.
Log File

We have written a class to write log files easily. Its source code can be seen and downloaded VB class for log file on GitHub.

'Author: Yan Naing Aye
'WebSite: http://cool-emerald.blogspot.sg/
'Updated: 2009 June 25
'-----------------------------------------------------------------------------
Imports System.IO
Public Class ClsLog
    Private mEnableLog As Boolean = False
    Private mLogFileDirectory As String = ""
    Private mLogFilePath As String = ""
    Private mLogFileLifeSpan As Integer = 0
    Private mLogFileFirstName As String = "AppName"
    Public Sub New()
        mEnableLog = False
        mLogFileDirectory = My.Application.Info.DirectoryPath
        mLogFileLifeSpan = 0
        mLogFileFirstName = My.Application.Info.AssemblyName
    End Sub
    Public Property LogFileLifeSpan() As Integer
        Get
            Return mLogFileLifeSpan
        End Get
        Set(ByVal value As Integer)
            mLogFileLifeSpan = IIf(value >= 0, value, 0)
        End Set
    End Property
    Public Property LogFileFirstName() As String
        Get
            Return mLogFileFirstName
        End Get
        Set(ByVal value As String)            
            mLogFileFirstName = value
        End Set
    End Property
    Public Property LogEnable() As Boolean
        Get
            Return mEnableLog
        End Get
        Set(ByVal value As Boolean)
            If value = True Then
                If Directory.Exists(Me.LogFileDirectory) Then
                    mEnableLog = value
                Else
                    mEnableLog = False
                    Throw New Exception("Invalid file directory.")
                End If
            Else
                mEnableLog = value
            End If
        End Set
    End Property
    Public Property LogFileDirectory() As String
        Get
            Return mLogFileDirectory
        End Get
        Set(ByVal value As String)
            value = Trim(value)
            If Directory.Exists(value) Then
                Dim i As Integer = value.Length - 1
                If (((value(i)) = "\") OrElse ((value(i)) = "/")) Then
                    value = value.Substring(0, i)
                End If
                mLogFileDirectory = value
            Else
                Throw New Exception("Invalid file directory.")
            End If
        End Set
    End Property
    Public ReadOnly Property LogFilePath() As String
        Get
            Return mLogFileDirectory & "\" & mLogFileFirstName & Format(Now, "-yyyy-MMM-dd") & ".log"
        End Get
    End Property
    Public Sub WriteLog(ByVal LogEntry As String)
        If mEnableLog = True Then
            mLogFilePath = mLogFileDirectory & "\" & mLogFileFirstName & Format(Now, "-yyyy-MMM-dd") & ".log"
            Dim objStreamWriter As StreamWriter = New StreamWriter(mLogFilePath, True)
            Try
                objStreamWriter.WriteLine(LogEntry)
            Catch ex As Exception
            Finally
                objStreamWriter.Close()
            End Try
        End If
    End Sub
    Public Sub WriteTimeAndLog(ByVal LogEntry As String)
        WriteLog(Now.ToLongTimeString & " " & LogEntry)
    End Sub
    Public Sub CleanupFiles()
        If mLogFileLifeSpan > 0 Then 'if life span is zero, there will be no cleaning up
            Try
                Dim LogFiles() As String = Directory.GetFiles(mLogFileDirectory)
                For Each LogFile As String In LogFiles
                    If (DateDiff("d", File.GetLastWriteTime(LogFile), Now) > mLogFileLifeSpan) _
                    AndAlso (Right(LogFile, 4) = ".log") Then
                        File.Delete(LogFile)
                    End If
                Next
            Catch ex As Exception
            End Try
        End If
    End Sub
End Class

Sunday, February 1, 2009

FAT32 Format

I want to use my removable hard disk on both Windows and Linux machines. The problem was that Linux does not support NTFS and I could not format my disk to FAT32 in Windows XP. Using "format x: /fs:fat32" command ended in vain because it was larger than 32 GB. I also tried to format in Windows Vista but it still did not work in Linux. Later, I found a small and easy to use freeware program called fat32format.exe that can format large hard disks very fast. Just partition the drive, then type "fat32format X:" where X is the partition letter. Formatting a drive in FAT32 will allow it to be read by other operating systems, such as Mac, Linux, older versions of Windows, etc.

Tuesday, January 20, 2009

Using Notify Icon in Visual Basic 2005


To add notify icon to system tray is much easier in VB2005 than VB6. Create a new Windows Application in VB2005. Add NotifyIcon control as shown in the following figure.


Select "NotifyIcon1" control. In its properties window, choose "Icon" and open your icon to be used. If you do not define an icon there, you will not see notify icon in the system tray.
To display the notify icon when you close your application, go to code view and enter the following code to FormClosing event.

Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing        
          If MessageBox.Show("Do you really want to exit?", "Exit", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.No Then            
                e.Cancel = True           
                Me.Visible = False
                NotifyIcon1.Visible = True
          End If        
    End Sub 

To display the application back when you double click the notify icon in the system tray, write the following code in MouseDoubleClick event of NotifyIcon1 control.

Private Sub NotifyIcon1_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick
          Me.Visible = True ' Show the form.
          Me.Activate() ' Activate the form.
          NotifyIcon1.Visible = False
End Sub

To close the application also from File menu and context menu. Add these controls.


Then add the code 'Me.Close()' to their click event so that it becomes ...

Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
          ' Close the form, which closes the application.
          Me.Close()
End Sub

Private Sub ContextMenuStrip1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ContextMenuStrip1.Click
          Me.Close()
End Sub

Select NotifyIcon1 control and define the ContextMenuStrip1 control in its ContestMenuStrip property so that the pop up menu will appear when you right click on the notify icon.

After that you can run the program. When you close the window, a message box will appear to confirm that you really want to exit. If you choose "No", the application will remain in the system tray on which you can double click to call back the application.

Sunday, January 18, 2009

Capturing and Sending Key -Using AJAX

AJAX is not a new programming language, but a technique for creating better, faster, and more interactive web applications. By using the key object -XMLHttpRequest of AJAX, we can create a dynamic webpage which can make a request and get a response from web server in the background without reloading the page. The user may not even notice that it is communicating invisibly.
Let us discuss an example that captures and sends the key input using AJAX. This example is based on the one that can be found in W3Schools site. There will be three files- keyCapture.html, keyCapture.js, and keyCapture.php.
First, we will create an HTML page called "keyCapture.html" that have a DIV element to display the message returned by the server. All JavaScript will be put in a separate file.


<html>
<head>
<title>Key Capture</title>
<script src='keyCapture.js'></script>
</head>
<body>
<form>
Press a key to send to server.
<div id='text1' style="font-size: 40px; color:blue;">
</div>
</form>
</body>
</html>

Second, the JavaScript file called "keyCapture.js" is created to capture keyboard input and send to the server using AJAX. It is explained in details.

var xmlHttp;
document.onkeypress = DisplayMsg;
function DisplayMsg(key_event) {
    var keyChar;
    if (document.all) {
        keyChar = String.fromCharCode(event.keyCode);
    }
    else if (document.getElementById) {
        keyChar = String.fromCharCode(key_event.which);
    }
    else if (document.layers) {
        keyChar = String.fromCharCode(key_event.which);
    }
    xmlHttp = GetXmlHttpObject();
    if (xmlHttp == null) {
        alert("Your Browser does not support AJAX!");
        return;
    }
    var url = "keyCapture.php";
    url = url + "?keyC=" + keyChar + "&sid=" + Math.random();
    xmlHttp.onreadystatechange = stateChanged;
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}

function stateChanged() { if (xmlHttp.readyState == 4) { document.getElementById('text1').innerHTML = xmlHttp.responseText; } } function GetXmlHttpObject() { var xmlHttp = null; try { // Firefox, Opera 8.0+, Safari xmlHttp = new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; }

There are three main parts in this JavaScript file.
1. Creating XMLHttpRequest object
2. To define a function to handle the data returned by the server
3. To send off a request to the server


1. Creating XMLHttpRequest object
Depending on browser, the method for creating XMLHttpRequest object can be different. ActiveXObject is used in Internet Explorer and XMLHttpRequest JavaScript object is used in other browsers. The following JavaScript function can be used to deal with different browsers.
function GetXmlHttpObject()
{
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}

In the function that wants to use the XMLHttpRequest object, we can just call this GetXmlHttpObject() function as
var xmlHttp
xmlHttp=GetXmlHttpObject();


If the object cannot be created, we can alert a message that AJAX is not supported.

if (xmlHttp==null)
  {
  alert ("Your browser does not support AJAX!");
  return;
  } 

2. To define a function to handle the data returned by the server
The following JavaScript define a function that will be called when the server response status has changed. The readyState property has five possible values (from 0 to 4) and it checks for request complete state (state value 4) before it process the response.


function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}

When the server response status has changed, the function stored in onreadystatechange property will be called automatically. It must be defined in the function that initiates the XMLHttpRequest as

xmlHttp.onreadystatechange=stateChanged;


3. To send off a request to the server
When we submit a request using "GET" method, the ids of the fields and values of that fields are sent in the url e.g.,
http://youraddress.com/keyCapture.php?id1=val1
We will modify the url of our php script using that format and add another ramdom value to make sure that cached version is not returned.


var url = "keyCapture.php";
url = url + "?keyC=" + keyChar + "&sid=" + Math.random();

By using the open() method and the send() method of the XMLHttpRequest object, a request can be sent to the server. The first argument of the open method can be GET or POST. The second argument is URL of the server-side script and third one specifies to handle the request asynchronously.

xmlHttp.open("GET", url, true);
xmlHttp.send(null);


Third, the server side script called "keyCapture.php" will be written in PHP as follow.

<?php
//get the parameter from URL
$k=$_GET["keyC"];
echo "Received: " . $k;
?>

Saturday, January 17, 2009

Capture Key Event in JavaScript

A friend of me wanted to control a hardware module that attached to a remote linux server using keyboard input in a client web page. She asked me how to do it. And I also didn't know :) We agreed to use JavaScript in client side and PHP on remote server. In the internet browser of the client computer, she didn't want to fill in and submit a form manually. That means key inputs must be captured directly and immediately sent to remote server to control the hardware accordingly.
After surfing for a while, a web page was found here about how to capture key inputs in JavaScript. Then we wrote a web page in PHP that sends key input directly. See the code that was written in "key.php".



<html>
<head>
<script language="JavaScript" type = "text/javascript">
<!--
document.onkeypress = DisplayMsg;
function DisplayMsg(key_event)
{
if (document.all) //Checks for IE 4.0 or later
{
document.form1.text1.value = String.fromCharCode(event.keyCode);
}
else if (document.getElementById) //checks for Netscape 6 or later
{
document.form1.text1.value = String.fromCharCode(key_event.which);
}
else if (document.layers) //Checks for Netscape 4
{
document.form1.text1.value = String.fromCharCode(key_event.which);
}
document.form1.submit();
}
//-->
</script>
<title>Capture Key Pressed</title>
</head>
<body>
<div style="display:none">
<form name="form1" action="key.php" method=GET>
<input type = "text" name = "text1">
</form>
</div>
<div style="font-size: 40px; color:blue;">
<?php
echo "Received: ";
echo $_GET["text1"];
?>
</div>
</body>
</html>


In this example, the problem in submitting the captured key is that the whole web page reloads everytime a key is pressed. It can be very slow when the page contains a lot of other contents. The better way is to use AJAX (Asynchronous JavaScript and XML) technique.

Sunday, December 7, 2008

Testing SB-900

At last weekend, I bought Nikon Autofocus Speedlight SB900 flash gun. But I was busy and I havn't tested it yet. In fact, I haven't finished the manual and I don't even know how to use it. Anyway, I have just made some trial shots. Have a look! The first one was taken using no flash light. She was using computer and having an apple under fluorescent lighting and some light from computer monitor. Even with ISO400, it took fairly slow shutter speed (with my kit) and the photo is blur.
The second one was using built in flash light.
The third photo was taken using reflected light of SB-900 from ceiling.

Sunday, November 23, 2008

Introduction to Squid

Squid is a free open source caching proxy software. Squid binaries for Windows can be downloaded from http://squid.acmeconsulting.it/.

Installing

In this example, squid-2.7.STABLE5-bin.zip is downloaded and extracted. Then "squid" directory was copied into C drive as "C:squid". Then go to "C:squidetc" directory, copy and rename the following files:
squid.conf.default ==> squid.conf
mime.conf.default ==> mime.conf
cachemgr.conf.default ==> cachemgr.conf
You can edit squid.conf as needed. In this example, it was left unchanged.
Open windows start menu and go to Start->Run. And enter "cmd" and click OK to launch "Comman Prompt" windows. Enter
cd C:squidsbin
in the command prompt to go to sbin folder that contains "squid.exe" program. Then enter a command in this format "squid -i [-f configfile] [-n servicename]" to installs the servicename Squid service using the configfile configuration file. (default configfile is "c:/squid/etc/squid.conf", default servicename is "Squid"). Here we used servicename as squid and configfile is at C:squidetcsquid.conf so you don't have to enter optional arguments. Use path with '/' char, NOT '' and you need to enter
squid -i -f c:/squid/etc/squid.conf  -n squid
and then a command to creates the cache directories as follow
squid -z -f c:/squid/etc/squid.conf

After that, enter
squid -O servicecommandline  -n squid

to set in Windows Registry the Squid servicename service command line.
Then open "Start->Control Panel->Administrative Tools->Services" and start "squid" service. Squid proxy server listens to port 3128 by default.

Client Side Setting


In the browser of client machine that wants to use proxy server, proxy settings have to be configured in some way. In this example Mozilla Frefox was used. In the Firefox browser, go to Tools menu -> Options... command -> Network tab -> click Settings... button inside connection frame and enter address of proxy server and port (3128 in this case).

In Linux machines, squid can be used as transparent proxy directly. But in windows machines, it is still a known limitation (Transparent Proxy: missing Windows non commercial interception driver).

Wednesday, October 22, 2008

Sending Email in VB2005

Here is an example code to send email using VB2005. We have used gmail to illustrate it and you need to have a gmail account to test it.


---------------------------------------------------
Imports System.Net.Mail Public Sub SendMail() Dim mail As New MailMessage() 'set the addresses mail.From = New MailAddress("yourname@gmail.com") mail.To.Add("DestinationAddress@gmail.com") 'set the content mail.Subject = "Sample Subject" mail.Body = "This is a body" 'send the message Dim smtp As New SmtpClient("smtp.gmail.com", 587) smtp.Credentials = New System.Net.NetworkCredential("yourname@gmail.com", "yourpassword") smtp.EnableSsl = True Try smtp.Send(mail) Catch ex As Exception MsgBox(ex.ToString()) End Try End Sub
---------------------------------------------------

Sunday, May 4, 2008

RS232-RS485 Converter

When you need to convert your serial communication from RS232 to RS422/RS485 or when you need to communicate to an RS485 device from a computer that uses RS232, you can use RS485 converter. This kind of converters are easily available. As an example, IC-485SN bidirectional converter is shown in the following figures.




As shown in the first figure, this RS485 converter can be configured by using two switches.
The first switch is used to select device mode. If the RS232 side (where DB25 Female connector is located) is connected to a Computer or a Data Terminal Equipment, it must switch to DTE. If that side is connected to a modem or a device (data communication equipment), it must switch to DCE.
The second switch is used to select transmitting and receiving mode.

1. TxON, RxON Mode


TxON, RxON is used for point to point operations. Transmit driver is always enabled and it is also always receiving. We can say, it is converting from RS232 to RS422. In RS232 side, RTS and CTS, DTR and DSR are loopback connected.
RS485 side connections are as follow:


Pin 1 = Tx+
Pin 2 = Tx-
Pin 3 = Rx-
Pin 4 = Rx+


2. TxRTS, RxON Mode


TxRTS, RxON is used for multidrop operations. Although it is always receiving, transmit driver is enabled only when RTS is high. For a DCE, CTS must be used instead of RTS. It can be used as four wire RS485 full duplex communication. In RS232 side, RTS and CTS, DTR and DSR are loopback connected.
RS485 side connections are as follow:


Pin 1 = Tx+
Pin 2 = Tx-
Pin 3 = Rx-
Pin 4 = Rx+


3. TxDTR/RTS, RxDSR/ON Mode


TxDTR/RTS, RxDSR/ON is used for RS485 half duplex communication. For a DTE, transmit drivers for data lines and busy lines are enabled only when RTS is true. When DTR is true, busy signal will be transmitted. On the receiving side, DSR will be true when a busy signal is received. For a DCE, CTS must be used instead of RTS. And DTR and DSR are inverse. In RS232 side, only RTS and CTS are loopback connected.
RS485 side connections are as follow:


Pin 1 = Data+
Pin 2 = Data-
Pin 3 = Busy-
Pin 4 = Busy+

The connections for DB 9 female and DB25 male Cable are as follow


Female DB9 -------------- Male DB25
pin 1 ---------------------- pin 8 .......... Black
pin 2 ---------------------- pin 3 .......... Brown
pin 3 ---------------------- pin 2 .......... Red
pin 4 ---------------------- pin 20 ........ Orange
pin 5 ---------------------- pin 7 .......... Yellow
pin 6 ---------------------- pin 6 .......... Green
pin 7 ---------------------- pin 4 .......... Blue
pin 8 ---------------------- pin 5 .......... Magenta
pin 9 ---------------------- pin 22 ........ Gray

Wednesday, April 23, 2008

Using PC Serial Port

Controlling and using PC serial port using Visual Basic programming is discussed. Many computers have a serial port. If your computer does not have one, you can buy a USB to RS232 converter.

There are three topics to be discussed here.
1. Using VB6
2. Using VB2005 (VB.NET2)
3. Serial Port as IO



Using VB6

MSComm ActiveX contorl can be used in VB6 to communicate through a serial port. Create a New project by selecting Standard Exe. Go to Project Menu and select Components command. Add Microsoft Comm Control 6.0 from Components dialog.

After OK has clicked, there will be MSComm control with a telephone icon in the Toolbox. Double click on this control to add it onto the Form. Its name will be "MSComm1" as shown below and you can change its settings in the Properties box near the bottom right corner.

In this example, its settings will not be changed in its properties box. But they will be changed in "Form_Load()" event. Double click on any blank space on the form to write in Form_Load() event as shown in the following code.


Private Sub Form_Load()
MSComm1.Settings = "9600,N,8,1"
MSComm1.RThreshold = 1
MSComm1.CommPort = 1
MSComm1.PortOpen = True
Text1.Text = ""
End Sub


The setting "9600,N,8,1" means that we will use Baud rate 9600, No parity, 8 data bit and 1 stop bit. RThreshold defines number of bytes in receive buffer to trigger receive event. In this example, Receive Event will be triggered even if there is only one byte in receive buffer. Comm port 1 of PC is used and opened here. A textbox is used to display the receive data. Another textbox and a Command button are added to the form to send data. Caption property of the Command button is changed to 'Send'.

Double click on that button and write the following code in its click event function.


Private Sub Command1_Click()
MSComm1.Output = "ABCD"
End Sub


Everytime the button is clicked, the data "ABCD" will be sent from the serial port. You can replace ABCD with any data you want to send. To receive data, OnComm event of MSComm control is used. Double click on MSComm control and write the following code in its event function. If OnComm Event is a data received event -comEvReceive, the Textbox will be updated with received data.


Private Sub MSComm1_OnComm()
If MSComm1.CommEvent = comEvReceive Then
  Text1.Text = Text1.Text & MSComm1.Input
End If
End Sub


After that, program will be as shown in the following figure.

Try to run the program. Data will be sent when the Send button is clicked.



Using VB2005


In VB2005, using Serial port is easier because SerialPort control is already in the toolbox. Create a Windows Application from File Menu -> New Project command. Double click on SerialPort Control in the Toolbox to add it onto the form.

Select the control and change its properties in the properties box. In the example, Name will be SerialPort1, BaudRates will be 9600, Databits will be 8, Parity will be None and StopBits will be One. ReceivedBytesThreshold defines number of bytes in receive buffer to trigger receive event. In this example, Receive Event will be triggered even if there is only one byte in receive buffer. Therefore ReceivedBytesThreshold will be 1. Comm port 1 of PC is used and PortName will be set to COM1.

Double click on the Form and write the following code in the Form Load Event.


CheckForIllegalCrossThreadCalls = False
SerialPort1.Open()


By doing so, the comm port will be opened at the program start. Normal Encoding of serial port control is ASCII. You can also change Encoding at the Form Load Event as follow.


SerialPort1.Encoding = System.Text.Encoding.Default


Add a Button to send data and a TextBox to display received data. Change Text property of the Button to Send. Double click on the Button and write the following code in its click event.


SerialPort1.Write("ABCD")


Everytime, the button is clicked, the data "ABCD" will be sent. You can replace ABCD with any data you want to send. To receive data, write the following code in the DataReceived event of SerialPort1.


TextBox1.Text &= SerialPort1.ReadExisting()


If you want to read the received data byte by byte, the following code can also be used.


Dim n As Int32
Dim i As Int32
Dim cmd As String
Dim c As String
n = SerialPort1.BytesToRead
For i = 1 To n
  c = Chr(SerialPort1.ReadChar())
  cmd &= c
Next
TextBox1.Text &= cmd


After that, the program will be as follow.

Then, you can try the program to send and receive data.
Sending Binary Data
The example above is for character data. For binary data whose ASCII code number greater than 127 can be manipulated as follow.


Dim a(3) As Byte
a(0) = &H41
a(1) = &H31
a(2) = &HFF
a(3) = &H80
SerialPort1.Write(a, 0, 4)


ReadChar cannot be used to receive binary data. ReadByte can be used instead as in the following example.


Dim n As Int32
Dim i As Int32
Dim cmd As String = ""
Dim c As String
n = SerialPort1.BytesToRead
For i = 1 To n
c = Chr(SerialPort1.ReadByte())
cmd &= c
Next
TextBox1.Text &= cmd


Getting Port List in Your PC
To list the all ports in your PC in a Combo box and to select the port number that had been saved in user setting, you can used the following code.


Dim ports As String() = SerialPort.GetPortNames()
Dim port As String
Array.Sort(ports)
cmbSerial.Items.Clear()
For Each port In ports
cmbSerial.Items.Add(port)
Next port
Dim index As Integer
index = cmbSerial.FindString(My.Settings.MCOM)
cmbSerial.SelectedIndex = index


Using Serial Port as IO

Besides Tx and Rx to send and receive data, there are two control outputs and four status inputs in a serial. RTS and DTR can be used as outputs. CTS, DSR, CD and RI can be used as inputs. If you don't need a lot of I/O in an application, serial port is a good choice for IO interface.

Related post: