Difference between revisions of "Visual Basic .net"

From ScienceZero
Jump to: navigation, search
(Simple pixel plotting)
Line 101: Line 101:
  
 
===Clearing the bitmap to a solid colour===
 
===Clearing the bitmap to a solid colour===
<code>
+
 
 
  gr.Clear(Color.Black)
 
  gr.Clear(Color.Black)
</code>
+
 
  
 
===Loading an image file into a picture box===
 
===Loading an image file into a picture box===
<code>
+
 
 
  PictureBox1.Image = New Bitmap("C:\path\somepic.jpg")
 
  PictureBox1.Image = New Bitmap("C:\path\somepic.jpg")
</code>
+
 
 
Note: .jpg .jpeg .gif .bmp .png .tiff .wmf files can also be used
 
Note: .jpg .jpeg .gif .bmp .png .tiff .wmf files can also be used
  
 
===Saving a picture box to an image file===
 
===Saving a picture box to an image file===
<code>
+
 
 
  PictureBox1.Image.Save("C:\path\savedpic.jpg", System.Drawing.Imaging.ImageFormat.Jpeg)
 
  PictureBox1.Image.Save("C:\path\savedpic.jpg", System.Drawing.Imaging.ImageFormat.Jpeg)
</code>
+
 
 
Note: .jpg .jpeg .gif .bmp .png .tiff .wmf files can also be used<br />
 
Note: .jpg .jpeg .gif .bmp .png .tiff .wmf files can also be used<br />
 
when using other formats, remember to change both the extension and the System.Drawing.Imaging.ImageFormat type
 
when using other formats, remember to change both the extension and the System.Drawing.Imaging.ImageFormat type
  
 
===Reading the mouse position within a picture box===
 
===Reading the mouse position within a picture box===
<code>
+
 
 
     Private Sub PictureBox1_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
 
     Private Sub PictureBox1_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
 
         Static pic As New Bitmap(PictureBox1.Width, PictureBox1.Height)
 
         Static pic As New Bitmap(PictureBox1.Width, PictureBox1.Height)
Line 126: Line 126:
 
         PictureBox1.Image = pic
 
         PictureBox1.Image = pic
 
     End Sub
 
     End Sub
</code>
+
 
  
 
===Drawing text on a bitmap (and then into a picture box)===
 
===Drawing text on a bitmap (and then into a picture box)===
<code>
+
 
 
         Dim bm As New Bitmap(PictureBox1.Width, PictureBox1.Height)
 
         Dim bm As New Bitmap(PictureBox1.Width, PictureBox1.Height)
 
         Dim gr As Graphics = Graphics.FromImage(bm)
 
         Dim gr As Graphics = Graphics.FromImage(bm)
Line 140: Line 140:
 
         gr.DrawString("Hello", myfont, Brushes.Black, XY)
 
         gr.DrawString("Hello", myfont, Brushes.Black, XY)
 
         PictureBox1.Image = bm
 
         PictureBox1.Image = bm
</code>
+
 
  
 
===Determining the width and height of text===
 
===Determining the width and height of text===
<code>
+
 
 
         Dim Textwidth, Textheight as Uint32
 
         Dim Textwidth, Textheight as Uint32
 
         Dim Textsize As Size
 
         Dim Textsize As Size
Line 151: Line 151:
 
         Textwidth = Textsize.Width
 
         Textwidth = Textsize.Width
 
         Textheight = Textsize.Height
 
         Textheight = Textsize.Height
</code>
+
 
  
 
===Loading a graphics file into a bitmap===
 
===Loading a graphics file into a bitmap===
<code>
+
 
 
         Dim bm As Bitmap
 
         Dim bm As Bitmap
 
         bm = Image.FromFile("mypic.png")
 
         bm = Image.FromFile("mypic.png")
</code>
+
 
  
 
==Files==
 
==Files==
  
 
===Reading text files line by line===
 
===Reading text files line by line===
<code>
+
 
 
  Dim f1 As Long
 
  Dim f1 As Long
 
  dim filestring as string
 
  dim filestring as string
Line 171: Line 171:
 
  Loop
 
  Loop
 
  FileClose(f1)
 
  FileClose(f1)
</code>
+
 
 
Note My.Application.Info.DirectoryPath & "\filename.txt" may be replaced by "C:\some_path\file.txt"<br />
 
Note My.Application.Info.DirectoryPath & "\filename.txt" may be replaced by "C:\some_path\file.txt"<br />
 
FileOpen(f1, My.Application.Info.DirectoryPath & "\filename.txt", OpenMode.Input, , OpenShare.Shared) may be used in order to not lock access to the file such that other programs may open it at the same time<br />
 
FileOpen(f1, My.Application.Info.DirectoryPath & "\filename.txt", OpenMode.Input, , OpenShare.Shared) may be used in order to not lock access to the file such that other programs may open it at the same time<br />
Line 179: Line 179:
  
 
===Writing text files line by line===
 
===Writing text files line by line===
<code>
+
 
 
  Dim f1 As Long
 
  Dim f1 As Long
 
  f1 = FreeFile()
 
  f1 = FreeFile()
Line 186: Line 186:
 
  Print(f1, "This is line 2")
 
  Print(f1, "This is line 2")
 
  FileClose(f1)
 
  FileClose(f1)
</code>
+
 
 
Note: FileOpen(f1, My.Application.Info.DirectoryPath & "\filename.txt", OpenMode.Output, , OpenShare.Shared) may be used in order to not lock access to the file such that other programs may open it at the same time<br />
 
Note: FileOpen(f1, My.Application.Info.DirectoryPath & "\filename.txt", OpenMode.Output, , OpenShare.Shared) may be used in order to not lock access to the file such that other programs may open it at the same time<br />
  
  
 
===loading data files into an array of bytes===
 
===loading data files into an array of bytes===
<code>
+
 
 
  Dim oFile As System.IO.FileInfo
 
  Dim oFile As System.IO.FileInfo
 
  oFile = New System.IO.FileInfo(My.Application.Info.DirectoryPath & "\file.dat")
 
  oFile = New System.IO.FileInfo(My.Application.Info.DirectoryPath & "\file.dat")
Line 201: Line 201:
 
  End If
 
  End If
 
  oFileStream.Close()
 
  oFileStream.Close()
</code>
+
 
  
  
 
===Writing binary files===
 
===Writing binary files===
<code>
+
 
 
  Dim FS As New IO.FileStream(My.Application.Info.DirectoryPath & "\file.dat", System.IO.FileMode.Create)
 
  Dim FS As New IO.FileStream(My.Application.Info.DirectoryPath & "\file.dat", System.IO.FileMode.Create)
 
  Dim BW As New IO.BinaryWriter(FS)
 
  Dim BW As New IO.BinaryWriter(FS)
Line 216: Line 216:
 
  BW.Close()
 
  BW.Close()
 
  FS.Close()
 
  FS.Close()
</code>
+
 
  
 
===Reading Binary Files===
 
===Reading Binary Files===
<code>
+
 
 
         Dim FS As New IO.FileStream(My.Application.Info.DirectoryPath & "\filename.bin", System.IO.FileMode.Open)
 
         Dim FS As New IO.FileStream(My.Application.Info.DirectoryPath & "\filename.bin", System.IO.FileMode.Open)
 
         Dim BW As New IO.BinaryReader(FS)
 
         Dim BW As New IO.BinaryReader(FS)
Line 243: Line 243:
 
         BW.Close()
 
         BW.Close()
 
         FS.Close()
 
         FS.Close()
</code>
+
 
  
 
===Using a "Browse" button===
 
===Using a "Browse" button===
<code>
+
 
 
  Dim ofd As New OpenFileDialog
 
  Dim ofd As New OpenFileDialog
 
  dim f1 as Long
 
  dim f1 as Long
Line 262: Line 262:
 
  End If
 
  End If
 
  End if
 
  End if
</code>
+
 
 
To separate a file path string, see [[#Getting just the path of a file given the entire path and filename as a string|this section]]
 
To separate a file path string, see [[#Getting just the path of a file given the entire path and filename as a string|this section]]
  
  
 
===Adding file paths to an array, from a directory===
 
===Adding file paths to an array, from a directory===
<code>
+
 
 
  files = System.IO.Directory.GetFiles("c:\somepath", "*.bmp")
 
  files = System.IO.Directory.GetFiles("c:\somepath", "*.bmp")
</code>
+
 
  
 
A more complex method
 
A more complex method
<code>
+
 
 
         Imports System.IO 'this line MUST be present and at the top of the code
 
         Imports System.IO 'this line MUST be present and at the top of the code
 
   
 
   
Line 289: Line 289:
 
         Return files.ToArray()
 
         Return files.ToArray()
 
     End Function
 
     End Function
</code>
+
 
 
"*.png|*.jpg|*.bmp|*.gif|*.tif" causes it to search only for these types, use *.* for all.<br />
 
"*.png|*.jpg|*.bmp|*.gif|*.tif" causes it to search only for these types, use *.* for all.<br />
 
use the AllDirectories option to include subdirectories
 
use the AllDirectories option to include subdirectories
  
 
===Reading XML files===
 
===Reading XML files===
<code>
+
 
 
  Imports System.Xml
 
  Imports System.Xml
 
  Imports System.IO
 
  Imports System.IO
Line 310: Line 310:
 
   End Sub
 
   End Sub
 
  End Class
 
  End Class
</code>
+
 
  
 
===Looping though all files in a directory===
 
===Looping though all files in a directory===
<code>
+
 
 
  Imports System.IO
 
  Imports System.IO
 
   
 
   
Line 330: Line 330:
 
     End Sub
 
     End Sub
 
  End Class
 
  End Class
</code>
+
 
  
 
==Arrays==
 
==Arrays==
Line 359: Line 359:
 
Note: large or slow loops may require you to insert an Application.Doevents() to update the window and keep the application responsive, this should generally be done every n loops as running it too frequently will slow things down by spending most of the time updating the window.
 
Note: large or slow loops may require you to insert an Application.Doevents() to update the window and keep the application responsive, this should generally be done every n loops as running it too frequently will slow things down by spending most of the time updating the window.
 
===Simple loop===
 
===Simple loop===
<code>
+
 
 
  Do
 
  Do
 
   'code to execute several times  
 
   'code to execute several times  
Line 365: Line 365:
 
   {Exit Do}      'exit the loop
 
   {Exit Do}      'exit the loop
 
  Loop
 
  Loop
</code>
+
 
  
 
===Do Loop While (run then check)===
 
===Do Loop While (run then check)===
<code>
+
 
 
  Do
 
  Do
 
   'code to loop here
 
   'code to loop here
 
   i = i + 1
 
   i = i + 1
 
  Loop While (i < 5)
 
  Loop While (i < 5)
</code>
+
 
  
 
===Do While (check then run)===
 
===Do While (check then run)===
<code>
+
 
 
  Do While i < 5
 
  Do While i < 5
 
   'code to loop here
 
   'code to loop here
 
   i = i + 1
 
   i = i + 1
 
  Loop
 
  Loop
</code>
+
 
  
 
===For===
 
===For===
<code>
+
 
 
  For i = 0 To 4
 
  For i = 0 To 4
 
   'code to loop here
 
   'code to loop here
Line 390: Line 390:
 
   {Exit For}      'continues execution after Next
 
   {Exit For}      'continues execution after Next
 
  Next
 
  Next
</code>
+
 
 
i will step by 1 each loop
 
i will step by 1 each loop
  
 
===For (custom step size)===
 
===For (custom step size)===
 
This example will cause i to increase by 2 on each loop
 
This example will cause i to increase by 2 on each loop
<code>
+
 
 
  For i = 0 To 4 step 2
 
  For i = 0 To 4 step 2
 
   'code to loop here
 
   'code to loop here
 
  Next
 
  Next
</code>
+
 
 
For down counting loops, step size must be negative, and variable type must be signed (unless all values are non-zero and positive).
 
For down counting loops, step size must be negative, and variable type must be signed (unless all values are non-zero and positive).
  
Line 409: Line 409:
 
===If===
 
===If===
 
====Equal====
 
====Equal====
<code>
+
 
 
  if i = 4 Then 'code here
 
  if i = 4 Then 'code here
 
   
 
   
Line 417: Line 417:
 
   'code line 2
 
   'code line 2
 
  End If
 
  End If
</code>
+
 
  
 
====Not equal====
 
====Not equal====
<code>
+
 
 
  if i <> 4 Then 'code here
 
  if i <> 4 Then 'code here
</code>
+
 
  
 
====Greater than====
 
====Greater than====
<code>
+
 
 
  if i > 4 Then 'code here
 
  if i > 4 Then 'code here
</code>
+
 
  
 
====Less than====
 
====Less than====
<code>
+
 
 
  if i < 4 Then 'code here
 
  if i < 4 Then 'code here
</code>
+
 
  
 
====Greater than or equal to====
 
====Greater than or equal to====
<code>
+
 
 
  if i >= 4 Then 'code here
 
  if i >= 4 Then 'code here
</code>
+
 
  
 
====Less than or equal to====
 
====Less than or equal to====
<code>
+
 
 
  if i <= 4 Then 'code here
 
  if i <= 4 Then 'code here
</code>
+
 
  
 
===If Else===
 
===If Else===
<code>
+
 
 
  if i = 4 Then 'code here Else 'code here
 
  if i = 4 Then 'code here Else 'code here
 
   
 
   
Line 454: Line 454:
 
   'code line 1
 
   'code line 1
 
  End If
 
  End If
</code>
+
 
  
 
===Select Case===
 
===Select Case===
<code>
+
 
 
  Select Case i
 
  Select Case i
 
   Case 0
 
   Case 0
Line 473: Line 473:
 
       'this code will run if i didn't match any of the above cases
 
       'this code will run if i didn't match any of the above cases
 
  End Select
 
  End Select
</code>
+
 
  
 
===Choose===
 
===Choose===
Line 524: Line 524:
  
 
===Rounding===
 
===Rounding===
<code>
+
 
 
  Math.Round(3.14159,2)
 
  Math.Round(3.14159,2)
</code>
+
 
 
Rounds to 2 decimal places, giving 3.14
 
Rounds to 2 decimal places, giving 3.14
  
 
===Seperating just the whole part of a number===
 
===Seperating just the whole part of a number===
<code>
+
 
 
  Int(3.14159)
 
  Int(3.14159)
</code>
+
 
 
Gives 3
 
Gives 3
  
 
===Seperating just the fractional part of a number===
 
===Seperating just the fractional part of a number===
<code>
+
 
 
  double pi
 
  double pi
 
  double frac
 
  double frac
 
  pi=Math.PI
 
  pi=Math.PI
 
  frac=pi-Int(pi)
 
  frac=pi-Int(pi)
</code>
+
 
 
Gives 0.14159
 
Gives 0.14159
  
 
===Modulus===
 
===Modulus===
 
This will return the remainder of a division
 
This will return the remainder of a division
<code>
+
 
 
  Dim i, counter as Uint32
 
  Dim i, counter as Uint32
 
   
 
   
Line 552: Line 552:
 
   counter = i Mod 5
 
   counter = i Mod 5
 
  Next
 
  Next
</code>
+
 
 
This example will cause counter to count from 0 to 4, back to 0, and though to 4 again.
 
This example will cause counter to count from 0 to 4, back to 0, and though to 4 again.
  
 
===Random integer between 2 values===
 
===Random integer between 2 values===
<code>
+
 
 
     Public Function randint(n1 As Long, n2 As Long) As Long
 
     Public Function randint(n1 As Long, n2 As Long) As Long
 
         randint = Int((((n2 + 1) - n1) * Rnd) + n1)
 
         randint = Int((((n2 + 1) - n1) * Rnd) + n1)
 
     End Function
 
     End Function
</code>
+
 
  
 
==Calling Windows API==
 
==Calling Windows API==
 
===Performance Counter (high resolution timer)===
 
===Performance Counter (high resolution timer)===
<code>
+
 
 
  Public Declare Function QueryPerformanceCounter Lib "kernel32.dll" (ByRef Counter As Long) As Integer
 
  Public Declare Function QueryPerformanceCounter Lib "kernel32.dll" (ByRef Counter As Long) As Integer
 
  Public Declare Function QueryPerformanceFrequency Lib "kernel32.dll" (ByRef counter As Long) As Integer
 
  Public Declare Function QueryPerformanceFrequency Lib "kernel32.dll" (ByRef counter As Long) As Integer
Line 576: Line 576:
 
  QueryPerformanceCounter(tStop)
 
  QueryPerformanceCounter(tStop)
 
  msgbox(CStr(CInt(1 / ((tStop - tStart) / curFreq))) & " Frames per second")
 
  msgbox(CStr(CInt(1 / ((tStop - tStart) / curFreq))) & " Frames per second")
</code>
+
 
  
 
===Sending keystrokes to applications===
 
===Sending keystrokes to applications===
<code>
+
 
 
     'Google Earth example with up arrow for 1 second
 
     'Google Earth example with up arrow for 1 second
 
     Private Const WM_KEYDOWN = &H100
 
     Private Const WM_KEYDOWN = &H100
Line 612: Line 612:
 
         SendMessage(GEarthHandle, WM_KEYUP, VK_UP, 0&) 'release UP
 
         SendMessage(GEarthHandle, WM_KEYUP, VK_UP, 0&) 'release UP
 
     End Sub
 
     End Sub
</code>
+
 
  
 
==RS-232==
 
==RS-232==
Line 627: Line 627:
  
 
===Adding a combo box with a list of available ports===
 
===Adding a combo box with a list of available ports===
<code>
+
 
 
     Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
 
     Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
 
         Dim str(System.IO.Ports.SerialPort.GetPortNames.Length - 1) As String
 
         Dim str(System.IO.Ports.SerialPort.GetPortNames.Length - 1) As String
Line 646: Line 646:
 
         SerialPort1.Open()
 
         SerialPort1.Open()
 
     End Sub
 
     End Sub
</code>
+
 
  
 
===Sending an entire array of bytes===
 
===Sending an entire array of bytes===
Line 654: Line 654:
  
 
===Reading a byte===
 
===Reading a byte===
<code>
+
 
 
  Dim serialbyte as Byte
 
  Dim serialbyte as Byte
 
  serialbyte=SerialPort1.ReadByte
 
  serialbyte=SerialPort1.ReadByte
</code>
+
 
  
 
===Reading n bytes already in the received buffer===
 
===Reading n bytes already in the received buffer===
<code>
+
 
 
  Dim serialbytes(n-1) as Byte
 
  Dim serialbytes(n-1) as Byte
 
  SerialPort1.Read(serialbytes,0,n)
 
  SerialPort1.Read(serialbytes,0,n)
</code>
+
 
 
This can be used with:<br />
 
This can be used with:<br />
<code>
+
 
 
While SerialPort1.BytesToRead < n
 
While SerialPort1.BytesToRead < n
</code><br />
+
<br />
 
beforehand.
 
beforehand.
  
Line 681: Line 681:
  
 
===Downloading HTML as a string from a web page===
 
===Downloading HTML as a string from a web page===
<code>
+
 
 
  Dim webClient As System.Net.WebClient = New System.Net.WebClient()
 
  Dim webClient As System.Net.WebClient = New System.Net.WebClient()
 
  Dim result As String
 
  Dim result As String
Line 693: Line 693:
 
  MsgBox(result)
 
  MsgBox(result)
 
  End If
 
  End If
</code>
+
 
  
 
===A simple TCP library (client)===
 
===A simple TCP library (client)===
<code>
+
 
 
  Imports System.Net
 
  Imports System.Net
 
  Imports System.Net.Sockets
 
  Imports System.Net.Sockets
Line 812: Line 812:
 
     End Function
 
     End Function
 
  End Class
 
  End Class
</code>
+
 
  
  
 
===A simple TCP library (server)===
 
===A simple TCP library (server)===
<code>
+
 
 
  Imports System.Net
 
  Imports System.Net
 
  Imports System.Net.Sockets
 
  Imports System.Net.Sockets
Line 912: Line 912:
 
         client.Close()
 
         client.Close()
 
     End Sub
 
     End Sub
</code>
+
 
  
 
===Sending UDP packets===
 
===Sending UDP packets===
<code>
+
 
 
     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
 
     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
 
         Dim endPoint As System.Net.IPEndPoint = New System.Net.IPEndPoint(System.Net.IPAddress.Parse("192.168.0.44"), 9000)
 
         Dim endPoint As System.Net.IPEndPoint = New System.Net.IPEndPoint(System.Net.IPAddress.Parse("192.168.0.44"), 9000)
Line 926: Line 926:
 
         Loop
 
         Loop
 
     End Sub
 
     End Sub
</code>
+
 
  
 
===Receiving UDP packets===
 
===Receiving UDP packets===
<code>
+
 
 
  Private Const port As Integer = 8000                          'Port number to send/recieve data on
 
  Private Const port As Integer = 8000                          'Port number to send/recieve data on
 
  Private receivingClient As System.Net.Sockets.UdpClient        'Client for handling incoming data
 
  Private receivingClient As System.Net.Sockets.UdpClient        'Client for handling incoming data
Line 952: Line 952:
 
     Loop
 
     Loop
 
  End Sub
 
  End Sub
</code>
+
 
  
 
== Conversion==
 
== Conversion==
Line 987: Line 987:
  
 
===Using the start of a string===
 
===Using the start of a string===
<code>
+
 
 
  dim str as string
 
  dim str as string
 
  dim outputstr as string
 
  dim outputstr as string
 
  str = "this is a string"
 
  str = "this is a string"
 
  outputstr = str.Substring(0, 4)
 
  outputstr = str.Substring(0, 4)
</code>
+
 
 
Starts at character index 0 (the first character), and reads 4 characters (including the first one), resulting in "this".<br />
 
Starts at character index 0 (the first character), and reads 4 characters (including the first one), resulting in "this".<br />
  
 
===Using the middle of a string===
 
===Using the middle of a string===
<code>
+
 
 
  dim str as string
 
  dim str as string
 
  dim outputstr as string
 
  dim outputstr as string
 
  str="this is a string"
 
  str="this is a string"
 
  outputstr=str.Substring(5, 4)
 
  outputstr=str.Substring(5, 4)
</code>
+
 
 
Starts at character index 5 (the 6th character), and reads 4 characters, resulting in "is a".<br />
 
Starts at character index 5 (the 6th character), and reads 4 characters, resulting in "is a".<br />
  
  
 
===Using the end of a string===
 
===Using the end of a string===
<code>
+
 
 
  dim str as string
 
  dim str as string
 
  dim outputstr as string
 
  dim outputstr as string
 
  str="this is a string"
 
  str="this is a string"
 
  outputstr=str1.Substring(str1.Length - 4, 4)
 
  outputstr=str1.Substring(str1.Length - 4, 4)
</code>
+
 
 
Starts 4 chacters before the end, and reads 4 characters, resulting in "ring".<br />
 
Starts 4 chacters before the end, and reads 4 characters, resulting in "ring".<br />
  
  
 
===Getting just the path of a file given the entire path and filename as a string===
 
===Getting just the path of a file given the entire path and filename as a string===
<code>
+
 
 
  PathStr.Substring(0, ofd.FileName.LastIndexOf("\")) & "\"
 
  PathStr.Substring(0, ofd.FileName.LastIndexOf("\")) & "\"
</code>
+
 
  
  
 
===Getting just the file name (with extension) of a file given the entire path and filename as a string===
 
===Getting just the file name (with extension) of a file given the entire path and filename as a string===
<code>
+
 
 
  System.IO.Path.GetFileName(PathStr)
 
  System.IO.Path.GetFileName(PathStr)
</code>
+
 
  
  
 
===Getting just the file name (without extension) of a file given the entire path and filename as a string===
 
===Getting just the file name (without extension) of a file given the entire path and filename as a string===
<code>
+
 
 
  System.IO.Path.GetFileNameWithoutExtension(PathStr)
 
  System.IO.Path.GetFileNameWithoutExtension(PathStr)
</code>
+
 
  
 
===Seperating the values from a time and date string===
 
===Seperating the values from a time and date string===
<code>
+
 
 
  curtimeanddate = Now
 
  curtimeanddate = Now
 
  yearstr = DateAndTime.Year(curtimeanddate)
 
  yearstr = DateAndTime.Year(curtimeanddate)
Line 1,041: Line 1,041:
 
  minutestr = DateAndTime.Minute(curtimeanddate)
 
  minutestr = DateAndTime.Minute(curtimeanddate)
 
  secondstr = DateAndTime.Second(curtimeanddate)
 
  secondstr = DateAndTime.Second(curtimeanddate)
</code>
+
 
 
Note: hours are in 24 hour/day.
 
Note: hours are in 24 hour/day.
  
Line 1,049: Line 1,049:
 
==Time==
 
==Time==
 
===Getting the current date and time===
 
===Getting the current date and time===
<code>
+
 
 
  timeanddatestr=Now
 
  timeanddatestr=Now
</code>
+
 
 
For processing this string, see the [[#Seperating the values from a time and date string|Seperating the values from a time and date string]] section
 
For processing this string, see the [[#Seperating the values from a time and date string|Seperating the values from a time and date string]] section
  
 
===Getting the number of seconds after midnight (includes fractional seconds)===
 
===Getting the number of seconds after midnight (includes fractional seconds)===
<code>
+
 
 
   Do
 
   Do
 
       Label1.Text = CStr(Microsoft.VisualBasic.Timer)
 
       Label1.Text = CStr(Microsoft.VisualBasic.Timer)
 
       Application.DoEvents()
 
       Application.DoEvents()
 
   Loop
 
   Loop
</code>
+
 
  
 
===Running code periodically===
 
===Running code periodically===
<code>
+
 
 
  Timer1.Interval = 1000 'number of milliseconds between calls
 
  Timer1.Interval = 1000 'number of milliseconds between calls
 
  Timer1.Enabled = True
 
  Timer1.Enabled = True
Line 1,070: Line 1,070:
 
     'your code here to run once a second
 
     'your code here to run once a second
 
  End Sub
 
  End Sub
</code>
+
 
 
(must add a timer to the form)
 
(must add a timer to the form)
  
 
===Stopwatch (milliseconds or high frequency ticks)===
 
===Stopwatch (milliseconds or high frequency ticks)===
 
example 1: timing code
 
example 1: timing code
<code>
+
 
 
  Dim stopWatch As New Stopwatch()
 
  Dim stopWatch As New Stopwatch()
 
   
 
   
Line 1,085: Line 1,085:
 
   
 
   
 
  msgbox(String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10))
 
  msgbox(String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10))
</code>
+
 
  
 
example 2: running code at 10Hz
 
example 2: running code at 10Hz
<code>
+
 
 
  Dim stopWatch As New Stopwatch
 
  Dim stopWatch As New Stopwatch
 
   
 
   
Line 1,099: Line 1,099:
 
   stopWatch.Restart()
 
   stopWatch.Restart()
 
  Loop
 
  Loop
</code>
+
 
  
 
example 3: running code at 2kHz
 
example 3: running code at 2kHz
<code>
+
 
 
  Dim stopWatch As New Stopwatch
 
  Dim stopWatch As New Stopwatch
 
  Dim freq, period As Long
 
  Dim freq, period As Long
Line 1,117: Line 1,117:
 
   stopWatch.Restart()
 
   stopWatch.Restart()
 
  Loop
 
  Loop
</code>
+
 
  
 
==Multimedia==
 
==Multimedia==
 
===Playing and stopping audio playback from an array of audio sample bytes===
 
===Playing and stopping audio playback from an array of audio sample bytes===
 
To begin playback:
 
To begin playback:
<code>
+
 
 
  My.Computer.Audio.Play(SampleArray, AudioPlayMode.Background)
 
  My.Computer.Audio.Play(SampleArray, AudioPlayMode.Background)
</code>
+
 
 
To stop playback:
 
To stop playback:
<code>
+
 
 
  My.Computer.Audio.Stop()
 
  My.Computer.Audio.Stop()
</code>
+
 
  
 
==Datatypes==
 
==Datatypes==
 
===Keeping variables between calls===
 
===Keeping variables between calls===
<code>
+
 
 
  Static countervar as Uint32
 
  Static countervar as Uint32
</code>
+
 
 
This will create a persistent variable called countervar
 
This will create a persistent variable called countervar
  
 
===Creating custom data types (structure)===
 
===Creating custom data types (structure)===
 
To set up:
 
To set up:
<code>
+
 
 
  Structure RGBtype
 
  Structure RGBtype
 
     Dim R As Byte
 
     Dim R As Byte
Line 1,145: Line 1,145:
 
     Dim B As Byte
 
     Dim B As Byte
 
  End Structure
 
  End Structure
</code>
+
 
 
To use:
 
To use:
<code>
+
 
 
  Dim pict(640, 480) As RGBtype
 
  Dim pict(640, 480) As RGBtype
 
  pict(0, 0).R = 100
 
  pict(0, 0).R = 100
Line 1,161: Line 1,161:
 
  value5 = pict(1, 2).G
 
  value5 = pict(1, 2).G
 
  value6 = pict(1, 2).B
 
  value6 = pict(1, 2).B
</code>
+
 
 
This will result in value1=100, value2=120, value3=150, value4=200, value5=220, value6=250  
 
This will result in value1=100, value2=120, value3=150, value4=200, value5=220, value6=250  
  
Line 1,171: Line 1,171:
 
! Range
 
! Range
 
|-  
 
|-  
| <code>Boolean</code>
+
| Boolean
| <code>System.Boolean</code>
+
| System.Boolean
 
| 4 bytes
 
| 4 bytes
 
| True or False
 
| True or False
 
|-  
 
|-  
| <code>Byte</code>
+
| Byte
| <code>System.Byte</code>
+
| System.Byte
 
| 1 byte
 
| 1 byte
 
| 0 to 255 (unsigned)
 
| 0 to 255 (unsigned)
 
|-
 
|-
|<code>SByte</code>
+
|SByte
| <code>System.SByte</code>
+
| System.SByte
 
| 1 byte  
 
| 1 byte  
 
| -128 through 127 (signed)  
 
| -128 through 127 (signed)  
 
|-  
 
|-  
| <code>Char</code>
+
| Char
| <code>System.Char</code>
+
| System.Char
 
| 2 bytes
 
| 2 bytes
 
| 0 to 65535 (unsigned)
 
| 0 to 65535 (unsigned)
 
|-  
 
|-  
| <code>Date</code>
+
| Date
| <code>System.DateTime</code>
+
| System.DateTime
 
| 8 bytes
 
| 8 bytes
 
| January 1, 1 CE to December 31, 9999
 
| January 1, 1 CE to December 31, 9999
 
|-  
 
|-  
| <code>Decimal</code>
+
| Decimal
| <code>System.Decimal</code>
+
| System.Decimal
 
| 12 bytes
 
| 12 bytes
 
| +/-79,228,162,514,264,337,593,543,950,335 with no decimal point; +/-7.9228162514264337593543950335 with 28 places to the right of the decimal; smallest non-zero number is +/-0.0000000000000000000000000001  
 
| +/-79,228,162,514,264,337,593,543,950,335 with no decimal point; +/-7.9228162514264337593543950335 with 28 places to the right of the decimal; smallest non-zero number is +/-0.0000000000000000000000000001  
 
|-  
 
|-  
| <code>Double</code>
+
| Double
| <code>System.Double</code>
+
| System.Double
 
| 8 bytes  
 
| 8 bytes  
 
| -1.79769313486231E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values  
 
| -1.79769313486231E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values  
 
|-  
 
|-  
| <code>Integer</code>
+
| Integer
| <code>System.Int32</code>
+
| System.Int32
 
| 4 bytes  
 
| 4 bytes  
 
| -2,147,483,648 to 2,147,483,647  
 
| -2,147,483,648 to 2,147,483,647  
 
|-  
 
|-  
| <code>UInteger</code>
+
| UInteger
| <code>System.UInt32</code>
+
| System.UInt32
 
| 4 bytes  
 
| 4 bytes  
 
| 0 through 4,294,967,295 (unsigned)  
 
| 0 through 4,294,967,295 (unsigned)  
 
|-  
 
|-  
| <code>Long</code>
+
| Long
| <code>System.Int64</code>
+
| System.Int64
 
| 8 bytes  
 
| 8 bytes  
 
| -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807  
 
| -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807  
 
|-  
 
|-  
| <code>ULong</code>
+
| ULong
| <code>System.UInt64</code>
+
| System.UInt64
 
| 8 bytes  
 
| 8 bytes  
 
| 0 through 18,446,744,073,709,551,615 (1.8...E+19) (unsigned)   
 
| 0 through 18,446,744,073,709,551,615 (1.8...E+19) (unsigned)   
 
|-  
 
|-  
| <code>Object</code>
+
| Object
| <code>System.Object</code> (class)  
+
| System.Object (class)  
 
| 4 bytes  
 
| 4 bytes  
| Any type can be stored in a variable of type <code>Object</code>
+
| Any type can be stored in a variable of type Object
 
|-  
 
|-  
| <code>Short</code>
+
| Short
| <code>System.Int16</code>
+
| System.Int16
 
| 2 bytes  
 
| 2 bytes  
 
| -32,768 to 32,767  
 
| -32,768 to 32,767  
 
|-  
 
|-  
| <code>UShort</code>
+
| UShort
| <code>System.UInt16</code>
+
| System.UInt16
 
| 2 bytes  
 
| 2 bytes  
 
| 0 through 65,535 (unsigned)   
 
| 0 through 65,535 (unsigned)   
 
|-  
 
|-  
| <code>Single</code>
+
| Single
| <code>System.Single</code>
+
| System.Single
 
| 4 bytes  
 
| 4 bytes  
 
| -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values  
 
| -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values  
 
|-  
 
|-  
| <code>String</code>
+
| String
| <code>System.String</code> (class)  
+
| System.String (class)  
 
| 10 bytes + (2 * string length)  
 
| 10 bytes + (2 * string length)  
 
| 0 to approximately two billion Unicode characters  
 
| 0 to approximately two billion Unicode characters  
 
|-  
 
|-  
 
| User-Defined Type (structure)  
 
| User-Defined Type (structure)  
| (inherits from <code>System.ValueType</code>)  
+
| (inherits from System.ValueType)  
 
| Sum of the sizes of its members  
 
| Sum of the sizes of its members  
 
| Each member of the structure has a range determined by its data type and independent of the ranges of the other members  
 
| Each member of the structure has a range determined by its data type and independent of the ranges of the other members  

Revision as of 14:31, 29 October 2015

<x> means always x
<x|y> means either x or y
{x} means x or nothing
{x|y} means either x or y or nothing

Exit <Do|For> means you can use either Exit Do or Exit For
{Continue Do} means that Continue Do is an optional statement

Contents

Application

Exit the application

Stop 'breakppoint that can be continued in Visual Studio
End  'terminate the application completely

Use this code to make sure any running loops are terminated:

  Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
      End
  End Sub

Events

If your code is not multithreaded you must at a suitable frequency do

Application.DoEvents()

Graphics

Simple pixel plotting

Dim pic As New Bitmap(256, 256)

For y As Integer = 0 To 99
  For x As Integer = 0 To 99
    pic.SetPixel(x, y, Color.Black)
  Next x

  picturebox1.Image = pic
  Application.DoEvents()
Next y

Reading a pixel

Dim pic As New Bitmap(256, 256)
Dim x,y,pixel as UInt32

pixel = pic.GetPixel(x, y)

Setting up graphics and drawing pixels, shapes, and colours

Dim bm As New Bitmap(PictureBox1.Width, PictureBox1.Height)
Dim gr As Graphics = Graphics.FromImage(bm)
Dim myBrush As Brush
Dim x, y, rectwidth, rectheight as UInt32

bm.SetPixel(10, 10, Color.FromArgb(255, 255, 0, 0))

Dim greenthickpen As New Pen(Color.FromArgb(255, 0, 255, 0), 10)
gr.DrawLine(greenthickpen, 20, 20, 40, 40)

gr.DrawArc(Pens.Blue, 80, 80, 20, 20, 0, 360)

gr.FillPie(Brushes.Black, 150, 150, 20, 20, 0, 360)

Dim rect As Rectangle
rect.Width = 10
rect.Height = 10
rect.X = 200
rect.Y = 200
gr.DrawRectangle(Pens.Black, rect)

myBrush = New SolidBrush(Color.FromArgb(255, 0, 255, 0))
gr.FillRectangle(myBrush, x, y, rectwidth, rectheight)

Dim triangle(2) As Point
triangle(0).X = 5
triangle(0).Y = 0 + 30
triangle(1).X = 0
triangle(1).Y = 5 + 30
triangle(2).X = 10
triangle(2).Y = 5 + 30
gr.FillPolygon(Brushes.Blue, triangle)

PictureBox1.Image = bm

Color.FromArgb(255, 255, 0, 0) is in the format of Alpha, Red, Green, Blue

Copies bitmap named bm into a 1D array called picArray as R,G,B,R,G,B,...

Dim bm As New Bitmap(PictureBox1.Width, PictureBox1.Height)
Dim pict2 As New Bitmap(PictureBox1.Width, PictureBox1.Height)
Dim gr As Graphics = Graphics.FromImage(bm)
Dim bmdR As System.Drawing.Imaging.BitmapData
Dim picArray() As Byte
Select Case bm.PixelFormat
	Case Imaging.PixelFormat.Format24bppRgb
	'Nothing to do here, this is our native format
	Case Else
	'Convert all other formats to our native format of RGB 8 bit per primary colour
	Pict2 = New Bitmap(bm.Width, bm.Height, Imaging.PixelFormat.Format24bppRgb)
	gr = Graphics.FromImage(Pict2)
		gr.DrawImageUnscaled(bm, 0, 0)
		bm = Pict2
	End Select
bmdR = bm.LockBits(New Rectangle(0, 0, bm.Width, bm.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bm.PixelFormat)
frameSize = bmdR.Stride * bmdR.Height
ReDim picArray(frameSize)
System.Runtime.InteropServices.Marshal.Copy(bmdR.Scan0, picArray, 0, frameSize)
bm.UnlockBits(bmdR)

Clearing the bitmap to a solid colour

gr.Clear(Color.Black)


Loading an image file into a picture box

PictureBox1.Image = New Bitmap("C:\path\somepic.jpg")

Note: .jpg .jpeg .gif .bmp .png .tiff .wmf files can also be used

Saving a picture box to an image file

PictureBox1.Image.Save("C:\path\savedpic.jpg", System.Drawing.Imaging.ImageFormat.Jpeg)

Note: .jpg .jpeg .gif .bmp .png .tiff .wmf files can also be used
when using other formats, remember to change both the extension and the System.Drawing.Imaging.ImageFormat type

Reading the mouse position within a picture box

   Private Sub PictureBox1_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
       Static pic As New Bitmap(PictureBox1.Width, PictureBox1.Height)

       pic.SetPixel(e.X, e.Y, Color.Black)
       PictureBox1.Image = pic
   End Sub


Drawing text on a bitmap (and then into a picture box)

       Dim bm As New Bitmap(PictureBox1.Width, PictureBox1.Height)
       Dim gr As Graphics = Graphics.FromImage(bm)
       Dim XY As Point
       Dim myfont As New Font("Comic Sans MS", 20, FontStyle.Regular)

       XY.X = 0
       XY.Y = 0

       gr.DrawString("Hello", myfont, Brushes.Black, XY)
       PictureBox1.Image = bm


Determining the width and height of text

       Dim Textwidth, Textheight as Uint32
       Dim Textsize As Size
       Dim myfont As New Font("Comic Sans MS", 20, FontStyle.Regular)

       Textsize = TextRenderer.MeasureText("sample text", myfont)
       Textwidth = Textsize.Width
       Textheight = Textsize.Height


Loading a graphics file into a bitmap

       Dim bm As Bitmap
       bm = Image.FromFile("mypic.png")


Files

Reading text files line by line

Dim f1 As Long
dim filestring as string
f1 = FreeFile()
FileOpen(f1, My.Application.Info.DirectoryPath & "\filename.txt", OpenMode.Input)
Do Until EOF(f1)
	filestring=LineInput(f1)
Loop
FileClose(f1)

Note My.Application.Info.DirectoryPath & "\filename.txt" may be replaced by "C:\some_path\file.txt"
FileOpen(f1, My.Application.Info.DirectoryPath & "\filename.txt", OpenMode.Input, , OpenShare.Shared) may be used in order to not lock access to the file such that other programs may open it at the same time

Writing text the preferred way (simpler and faster)

My.Computer.FileSystem.WriteAllText(My.Application.Info.DirectoryPath & "\programfile.txt", ProgramTxt.Text, False)

Writing text files line by line

Dim f1 As Long
f1 = FreeFile()
FileOpen(f1, My.Application.Info.DirectoryPath & "\filename.txt", OpenMode.Output)
Print(f1, "This is line 1")
Print(f1, "This is line 2")
FileClose(f1)

Note: FileOpen(f1, My.Application.Info.DirectoryPath & "\filename.txt", OpenMode.Output, , OpenShare.Shared) may be used in order to not lock access to the file such that other programs may open it at the same time


loading data files into an array of bytes

Dim oFile As System.IO.FileInfo
oFile = New System.IO.FileInfo(My.Application.Info.DirectoryPath & "\file.dat")
Dim oFileStream As System.IO.FileStream = oFile.OpenRead()
Dim lBytes As Long = oFileStream.Length
If (lBytes > 0) Then
	ReDim fileData(lBytes - 1)
	oFileStream.Read(fileData, 0, lBytes)
End If
oFileStream.Close()


Writing binary files

Dim FS As New IO.FileStream(My.Application.Info.DirectoryPath & "\file.dat", System.IO.FileMode.Create)
Dim BW As New IO.BinaryWriter(FS)
Dim bytevar, bytearray(99) As Byte

BW.Write(bytevar)	'writes a single byte
BW.Write(bytearray)	'writes a whole array of bytes
BW.Write(bytearray,0,100)	'writes 100 bytes of an array starting from position 0

BW.Close()
FS.Close()


Reading Binary Files

       Dim FS As New IO.FileStream(My.Application.Info.DirectoryPath & "\filename.bin", System.IO.FileMode.Open)
       Dim BW As New IO.BinaryReader(FS)
       Dim bytevar As Byte
       Dim bytearray(99) As Byte
       Dim filelen, i As UInt32

       filelen = BW.BaseStream.Length

       For i = 0 To filelen - 1
           bytevar = BW.ReadByte() 'reads a single byte
       Next

       BW.Close()
       FS.Close()

       FS = New IO.FileStream(My.Application.Info.DirectoryPath & "\filename.bin", System.IO.FileMode.Open)
       BW = New IO.BinaryReader(FS)

       bytearray = BW.ReadBytes(100) 'reads 100 bytes
       i = BW.ReadUInt32   'reads 4 bytes

       BW.Close()
       FS.Close()


Using a "Browse" button

Dim ofd As New OpenFileDialog
dim f1 as Long
If ofd.ShowDialog() = Windows.Forms.DialogResult.OK Then
	f1 = FreeFile()
	Try
		FileOpen(f1, ofd.FileName, OpenMode.Input)
	Catch ex As Exception
		MsgBox(ex.Message)
		err = 1
	End Try

	If err = 0 Then
		'read the file here
	End If
End if

To separate a file path string, see this section


Adding file paths to an array, from a directory

files = System.IO.Directory.GetFiles("c:\somepath", "*.bmp")


A more complex method

       Imports System.IO 'this line MUST be present and at the top of the code

       files = GetFiles("C:\somepath","*.png|*.jpg|*.bmp|*.gif|*.tif", SearchOption.TopDirectoryOnly)

   Private Function GetFiles(ByVal path As String, ByVal searchPattern As String, ByVal SearchOption As SearchOption) As String()
       Dim searchPatterns() = searchPattern.Split("|")
       Dim sp As String
       Dim files As New List(Of String)

       For Each sp In searchPatterns
           files.AddRange(System.IO.Directory.GetFiles(path, sp, SearchOption))
       Next

       files.Sort()
       Return files.ToArray()
   End Function

"*.png|*.jpg|*.bmp|*.gif|*.tif" causes it to search only for these types, use *.* for all.
use the AllDirectories option to include subdirectories

Reading XML files

Imports System.Xml
Imports System.IO

Public Class Form1

   Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
       Dim xDoc As XmlDocument = New XmlDocument()
       'this will create an array called coordinates with 1 entry for every time a tag with the text coordinates is found. Each entry will contain the text between the opening and closing tag of this name
       Dim coordinates As XmlNodeList = xDoc.GetElementsByTagName("coordinates")
       Dim CoordinatesString As String

       xDoc.Load("c:\test.kml")
       CoordinatesString = coordinates(coordinates.Count - 1).InnerXml    'this will load the contents of the last occurrence of the coordinates tag
  End Sub
End Class


Looping though all files in a directory

Imports System.IO

Public Class Form1
   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
       Dim dir As String = "e:\frames"
       Dim di As New DirectoryInfo(dir)
       Dim fiArr As FileInfo() = di.GetFiles()
       Dim fri As FileInfo

       For Each fri In fiArr
           PictureBox1.Image = New Bitmap(dir & "\" & fri.Name)
           Application.DoEvents()
           System.Threading.Thread.Sleep(40)
       Next fri
   End Sub
End Class


Arrays

Initialize array in line

Dim words() As String = {"zero", "one", "two"}

Threading / Parallel

Start a new thread

Dim player As New System.Threading.Thread(AddressOf midiPLayer)

player.Start()
Do
    System.Threading.Thread.Sleep(100)
    Application.DoEvents()
Loop While player.IsAlive

Distribute tasks automatically on all available cores

Imports System.Threading
Imports System.Threading.Tasks

Parallel.For(0, yRes - 1, Function(n) mandelbrotline(n, cr + xr, ci + yr, mandN, xRes, xStp, yStp, picarray))

n will iterate from 0 to yres -1 in no particular order
Requires .net 4 or Parallel extensions on .net 3.5

Loops

See conditional codes for loop checks

Note: large or slow loops may require you to insert an Application.Doevents() to update the window and keep the application responsive, this should generally be done every n loops as running it too frequently will slow things down by spending most of the time updating the window.

Simple loop

Do
  'code to execute several times 
  {Continue Do}  'jump to the top of the loop
  {Exit Do}      'exit the loop
Loop


Do Loop While (run then check)

Do
  'code to loop here
  i = i + 1
Loop While (i < 5)


Do While (check then run)

Do While i < 5
  'code to loop here
  i = i + 1
Loop


For

For i = 0 To 4
  'code to loop here
  {Continue For}  'skips to the next iteration
  {Exit For}      'continues execution after Next
Next

i will step by 1 each loop

For (custom step size)

This example will cause i to increase by 2 on each loop

For i = 0 To 4 step 2
  'code to loop here
Next

For down counting loops, step size must be negative, and variable type must be signed (unless all values are non-zero and positive).

Conditionals

Never compare floating-point variables for equality or assume that any floating-point variable will be accurate to a fixed number of digits without understanding the complexities of rounding and representing real numbers in a digital format.

Wrong: if a = b then ...
Right: if Math.Abs(a - b) < 0.0001 then

If

Equal

if i = 4 Then 'code here

'multiline 
if i = 4 Then
  'code line 1
  'code line 2
End If


Not equal

if i <> 4 Then 'code here


Greater than

if i > 4 Then 'code here


Less than

if i < 4 Then 'code here


Greater than or equal to

if i >= 4 Then 'code here


Less than or equal to

if i <= 4 Then 'code here


If Else

if i = 4 Then 'code here Else 'code here

if i = 4 Then
  'code line 1
  'code line 2
Else
  'code line 1
End If


Select Case

Select Case i
  Case 0
     'this code will run if i=0
     {Exit Select} 'continues execution after End Select
  Case 1
     'this code will run if i=1
  Case 2,3,4
     'this code will run if i is one of 2,3,4
  Case 5 To 10
     'this code will run if i is one of 5,6,7,8,9,10
  Case 11 To 20, is < -1 
     'this code will run if i is 11 to 20 or less than -1
  Case Else
     'this code will run if i didn't match any of the above cases
End Select


Choose

Dim i = 1

Do While i < 5
  MsgBox(Choose(i, "one", "two", "three", "four", "five"))
  i = i + 1 
Loop

Math

General computation

+ Addition
- Subtraction
* Multiplication
/ Division (will round integer divisions)
\ Integer division (rounded down to nearest whole value)
Math.Sqrt(value) Square Root
Math.Pow(x,y) x to the power of y (xy)
Math.Sin(AngleInRadians) Sine
Math.Cos(AngleInRadians) Cosine
Math.Tan(AngleInRadians) Tangent
Math.Floor(x) Rounds x down to an Integer
Math.Ceiling(x) Rounds x up to an Integer

Rounding

Math.Round(3.14159,2)

Rounds to 2 decimal places, giving 3.14

Seperating just the whole part of a number

Int(3.14159)

Gives 3

Seperating just the fractional part of a number

double pi
double frac
pi=Math.PI
frac=pi-Int(pi)

Gives 0.14159

Modulus

This will return the remainder of a division

Dim i, counter as Uint32

For i = 0 to 9
  counter = i Mod 5
Next

This example will cause counter to count from 0 to 4, back to 0, and though to 4 again.

Random integer between 2 values

   Public Function randint(n1 As Long, n2 As Long) As Long
       randint = Int((((n2 + 1) - n1) * Rnd) + n1)
   End Function


Calling Windows API

Performance Counter (high resolution timer)

Public Declare Function QueryPerformanceCounter Lib "kernel32.dll" (ByRef Counter As Long) As Integer
Public Declare Function QueryPerformanceFrequency Lib "kernel32.dll" (ByRef counter As Long) As Integer

Dim curFreq, tStart, tStop As UInt64
QueryPerformanceFrequency(curFreq)
QueryPerformanceCounter(tStart)

...code to be timed...

QueryPerformanceCounter(tStop)
msgbox(CStr(CInt(1 / ((tStop - tStart) / curFreq))) & " Frames per second")


Sending keystrokes to applications

   'Google Earth example with up arrow for 1 second
   Private Const WM_KEYDOWN = &H100
   Private Const WM_KEYUP = &H101
   Private Const VK_SPACE = &H20
   Private Const VK_CONTROL = &H11
   Private Const VK_LEFT = &H25
   Private Const VK_UP = &H26
   Private Const VK_RIGHT = &H27
   Private Const VK_DOWN = &H28

   Declare Auto Function FindWindow Lib "USER32.DLL" (ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr 'Get a handle to an application window.
   Declare Auto Function SetForegroundWindow Lib "USER32.DLL" (ByVal hWnd As IntPtr) As Boolean        'Activate an application window.
   Private Declare Auto Function SendMessage Lib "user32.dll" (ByVal hwnd As IntPtr, ByVal wMsg As Int32, ByVal wParam As Int32, ByVal lParam As Int32) As Int32

   Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
       'Get a handle to the GEarth application. The window class
       'and window name were obtained using the Spy++ (C:\Program Files\Microsoft Visual Studio 12.0\Common7\Tools\spyxx.exe) tool.
       Dim GEarthHandle As IntPtr = FindWindow("QWidget", "Google Earth")

       'Verify that GEarth is a running process.
       If GEarthHandle = IntPtr.Zero Then
           MsgBox("GEarth is not running.")
           Return
       End If

       'Make GEarth the foreground application
       SetForegroundWindow(GEarthHandle)

       SendMessage(GEarthHandle, WM_KEYDOWN, VK_UP, 0&) 'press UP
       System.Threading.Thread.Sleep(1000) '1 second
       SendMessage(GEarthHandle, WM_KEYUP, VK_UP, 0&) 'release UP
   End Sub


RS-232

Setting up a serial port

Dim SerialPort1 As New System.IO.Ports.SerialPort

SerialPort1.PortName = "COM1"
SerialPort1.BaudRate = "9600"
SerialPort1.DataBits = 8
SerialPort1.Parity = System.IO.Ports.Parity.None
SerialPort1.StopBits = 1
SerialPort1.Handshake = System.IO.Ports.Handshake.None
SerialPort1.Open()

Adding a combo box with a list of available ports

   Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
       Dim str(System.IO.Ports.SerialPort.GetPortNames.Length - 1) As String
       Dim i, len As UInt32

       str = System.IO.Ports.SerialPort.GetPortNames()
       len = str.Length

       For i = 0 To len - 1
           ComboBox1.Items.Add(str(i))
       Next

       ComboBox1.SelectedIndex = 0
   End Sub

   Private Sub btnConnect_Click(sender As Object, e As EventArgs) Handles btnConnect.Click
       SerialPort1.PortName = ComboBox1.SelectedItem
       SerialPort1.Open()
   End Sub


Sending an entire array of bytes

SerialPort1.Write(bytearray, 0, bytearray.Count)

0 indicated the index to start reading the array, bytearray.Count is the number of bytes to transmit.
This operation is incredibly fast compared to looping through the array and sending 1 byte at a time. This is especially useful for high speed serial ports.

Reading a byte

Dim serialbyte as Byte
serialbyte=SerialPort1.ReadByte


Reading n bytes already in the received buffer

Dim serialbytes(n-1) as Byte
SerialPort1.Read(serialbytes,0,n)

This can be used with:

While SerialPort1.BytesToRead < n
beforehand.

Network / Internet

POST text to a PHP program on a WEB server

Imports System.Net
Dim client As WebClient = New WebClient()
Dim encoding As New System.Text.ASCIIEncoding()
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded")
client.UploadData(URL & "net2.php", "POST", encoding.GetBytes("data=" & text))
client.Dispose()


Downloading HTML as a string from a web page

Dim webClient As System.Net.WebClient = New System.Net.WebClient()
Dim result As String

Try
	result = webClient.DownloadString("http://www.google.com")
Catch ex As Exception
	MsgBox(ex.Message)
End Try
If result <> "" Then
	MsgBox(result)
End If


A simple TCP library (client)

Imports System.Net
Imports System.Net.Sockets

Public Class Form1
    Dim tnSocket As Socket
    Dim encText As New System.Text.UTF8Encoding()

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim str As String
	
	Connect("64.94.18.122", 80)
	
	str = "sample string"

	SendBytes(encText.GetBytes(str), str.Length)

	Disconnect()
    End Sub
    

    Public Function Connect(ip As String, port As UInt32) As Int32
        Dim remoteIPAddress As IPAddress
        Dim ep As IPEndPoint
        Dim retval As Int32

        retval = 1
        remoteIPAddress = IPAddress.Parse(ip)
        ep = New IPEndPoint(remoteIPAddress, port)
        tnSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

        Try
            tnSocket.Connect(ep)
            While tnSocket.Connected = False
                Application.DoEvents()
            End While
        Catch oEX As SocketException
            retval = -1
        End Try

        Return retval
    End Function

    Public Function WaitForData() As Int32
        Dim available As Int32

        Do
            Try
                available = tnSocket.Available
            Catch oEX As SocketException
                available = -1
                Exit Do
            End Try
            Application.DoEvents()
        Loop While available = 0

        Return available
    End Function

    Public Function WaitForLength(length As UInt32) As Int32
        Dim available As Int32
        Dim retval As Int32

        retval = 1
        Do
            Try
                available = tnSocket.Available
            Catch oEX As SocketException
                retval = -1
                Exit Do
            End Try
            Application.DoEvents()
        Loop While available <> length

        Return retval
    End Function

    Public Function ReadBytes(databytes() As Byte, length As Int32) As Int32
        Dim retval As Int32

        retval = 1
        Try
            tnSocket.Receive(databytes, length, 0)
        Catch oEX As SocketException
            retval = -1
        End Try

        Return retval
    End Function

    Public Function SendBytes(databytes() As Byte, length As Int32) As Int32
        Dim retval As Int32

        retval = 1
        Try
            tnSocket.Send(databytes, length, SocketFlags.None)
        Catch oEX As SocketException
            retval = -1
        End Try

        Return retval
    End Function

    Public Function Disconnect() As Int32
        Dim retval As Int32

        retval = 1
        Try
            tnSocket.Disconnect(False)
        Catch oEX As SocketException
            retval = -1
        End Try

        Return retval
    End Function
End Class


A simple TCP library (server)

Imports System.Net
Imports System.Net.Sockets

   Dim client As TcpClient
   Dim stream As NetworkStream


   Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
       Dim available As UInt32
       Dim bytes(1023) As Byte

       StartServer(4445)

       Do
           available = WaitForData()
           ReadBytes(bytes, available)
           SendBytes(bytes, available)

           Application.DoEvents()
       Loop
   End Sub


   Private Sub StartServer(port As UInt32)
       'Set the TcpListener on a port
       Dim server As New TcpListener(IPAddress.Any, port)

       'Start listening for client requests.
       server.Start()

       'Enter the listening loop. 
       'Waiting for a connection

       'Perform a blocking call to accept requests.
       While server.Pending = False
           System.Threading.Thread.Sleep(100)
           Application.DoEvents()
       End While

       'You could also user server.AcceptSocket() here. 
       client = server.AcceptTcpClient()
       'Connected!

       'Get a stream object for reading and writing 
       stream = client.GetStream()
   End Sub


   Private Function WaitForData()  'returns the number of available bytes
       Dim available As UInt32

       'Check for available data 
       Do
           available = client.Available
           If available = 0 Then
               System.Threading.Thread.Sleep(10)
               Application.DoEvents()
           End If
       Loop While available = 0

       Return available
   End Function


   Private Function ReadByte()
       Dim data(0) As Byte

       stream.Read(data, 0, 1)

       Return data(0)
   End Function


   Private Sub SendByte(bytevalue As Byte)
       Dim data(0) As Byte

       data(0) = bytevalue

       stream.Write(data, 0, 1)
   End Sub


   Private Sub ReadBytes(bytearray() As Byte, length As UInt32)
       stream.Read(bytearray, 0, length)
   End Sub


   Private Sub SendBytes(bytearray() As Byte, length As UInt32)
       stream.Write(bytearray, 0, length)
   End Sub


   Private Sub CloseConnection()
       client.Close()
   End Sub


Sending UDP packets

   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
       Dim endPoint As System.Net.IPEndPoint = New System.Net.IPEndPoint(System.Net.IPAddress.Parse("192.168.0.44"), 9000)
       Dim data() As Byte={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19}

       sender = New System.Net.Sockets.UdpClient(9000)

       Do
               sender.Send(data, 20, endPoint)
       Loop
   End Sub


Receiving UDP packets

Private Const port As Integer = 8000                           'Port number to send/recieve data on
Private receivingClient As System.Net.Sockets.UdpClient         'Client for handling incoming data

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim endPoint As System.Net.IPEndPoint = New System.Net.IPEndPoint(System.Net.IPAddress.Any, port) 'Listen for incoming data from any IP address on the specified port
    Dim data(5000) As Byte   'buffer for storing incoming bytes
    Dim bytesavailable, i As UInt32
    receivingClient = New System.Net.Sockets.UdpClient(port)

    Do                                                    'Setup an infinite loop
        Do
            bytesavailable = receivingClient.Available
        Loop While bytesavailable = 0

        data = receivingClient.Receive(endPoint)                     'Receive incoming bytes

        For i = 0 To bytesavailable - 1
            TextBox1.AppendText(data(i).ToString("X2") & " ")
        Next
        Application.DoEvents()
    Loop
End Sub


Conversion

To text

dim var as integer = 1103
var.ToString("D5") -> "01103" (decimal)
var.ToString("F2") -> "1103.00" (with fraction)
var.ToString("x") -> "ff4" (hex)
var.ToString("X") -> "0FF4" (hex)
var.ToString("X4") -> "0FF4" (hex)
Convert.ToString(var, 16) -> "ff4"
Convert.ToString(var, 2) -> "10001001111"
Convert.ToString(var, 2).PadLeft(16, "0") -> "0000010001001111"

From text

Convert.ToInt32("ff4", 16) -> 1103
Convert.ToInt32("11111", 2) -> 31

From an array of bytes to a base data type

Dim n As Single = BitConverter.ToSingle(array, index)

From a base data type to an array of bytes

Dim array As Byte( ) = BitConverter.GetBytes(argument)

Strings

Finding text in a string

New method:

"this is a string".IndexOf("is")

returns (zero based character position number) 5. This function returns -1 when not found.

VB6 method:

InStr("this is a string", "is")

returns (character position number) 6. This function returns 0 when not found.

Using the start of a string

dim str as string
dim outputstr as string
str = "this is a string"
outputstr = str.Substring(0, 4)

Starts at character index 0 (the first character), and reads 4 characters (including the first one), resulting in "this".

Using the middle of a string

dim str as string
dim outputstr as string
str="this is a string"
outputstr=str.Substring(5, 4)

Starts at character index 5 (the 6th character), and reads 4 characters, resulting in "is a".


Using the end of a string

dim str as string
dim outputstr as string
str="this is a string"
outputstr=str1.Substring(str1.Length - 4, 4)

Starts 4 chacters before the end, and reads 4 characters, resulting in "ring".


Getting just the path of a file given the entire path and filename as a string

PathStr.Substring(0, ofd.FileName.LastIndexOf("\")) & "\"


Getting just the file name (with extension) of a file given the entire path and filename as a string

System.IO.Path.GetFileName(PathStr)


Getting just the file name (without extension) of a file given the entire path and filename as a string

System.IO.Path.GetFileNameWithoutExtension(PathStr)


Seperating the values from a time and date string

curtimeanddate = Now
yearstr = DateAndTime.Year(curtimeanddate)
monthstr = DateAndTime.Month(curtimeanddate)
dayofmonthstr = DateAndTime.Day(curtimeanddate)
hourstr = DateAndTime.Hour(curtimeanddate)
minutestr = DateAndTime.Minute(curtimeanddate)
secondstr = DateAndTime.Second(curtimeanddate)

Note: hours are in 24 hour/day.

Converting a string to a number in other locales

n = Single.Parse(text, System.Globalization.NumberFormatInfo.InvariantInfo)

Time

Getting the current date and time

timeanddatestr=Now

For processing this string, see the Seperating the values from a time and date string section

Getting the number of seconds after midnight (includes fractional seconds)

 Do
     Label1.Text = CStr(Microsoft.VisualBasic.Timer)
     Application.DoEvents()
 Loop


Running code periodically

Timer1.Interval = 1000 'number of milliseconds between calls
Timer1.Enabled = True

Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
    'your code here to run once a second
End Sub

(must add a timer to the form)

Stopwatch (milliseconds or high frequency ticks)

example 1: timing code

Dim stopWatch As New Stopwatch()

stopWatch.Start()
System.Threading.Thread.Sleep(1000)
stopWatch.Stop()

Dim ts As TimeSpan = stopWatch.Elapsed

msgbox(String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10))


example 2: running code at 10Hz

Dim stopWatch As New Stopwatch

stopWatch.Start()
Do
  While stopWatch.ElapsedMilliseconds < 100
  End While

  'code
  stopWatch.Restart()
Loop


example 3: running code at 2kHz

Dim stopWatch As New Stopwatch
Dim freq, period As Long

freq = stopWatch.Frequency
period = freq / 2000

stopWatch.Start()
Do
  While stopWatch.ElapsedTicks < period
  End While

  'code
  stopWatch.Restart()
Loop


Multimedia

Playing and stopping audio playback from an array of audio sample bytes

To begin playback:

My.Computer.Audio.Play(SampleArray, AudioPlayMode.Background)

To stop playback:

My.Computer.Audio.Stop()


Datatypes

Keeping variables between calls

Static countervar as Uint32

This will create a persistent variable called countervar

Creating custom data types (structure)

To set up:

Structure RGBtype
    Dim R As Byte
    Dim G As Byte
    Dim B As Byte
End Structure

To use:

Dim pict(640, 480) As RGBtype
pict(0, 0).R = 100
pict(0, 0).G = 120
pict(0, 0).B = 150
pict(1, 2).R = 200
pict(1, 2).G = 220
pict(1, 2).B = 250
value1 = pict(0, 0).R
value2 = pict(0, 0).G
value3 = pict(0, 0).B
value4 = pict(1, 2).R
value5 = pict(1, 2).G
value6 = pict(1, 2).B

This will result in value1=100, value2=120, value3=150, value4=200, value5=220, value6=250

Datatype information

VB type .net type Size Range
Boolean System.Boolean 4 bytes True or False
Byte System.Byte 1 byte 0 to 255 (unsigned)
SByte System.SByte 1 byte -128 through 127 (signed)
Char System.Char 2 bytes 0 to 65535 (unsigned)
Date System.DateTime 8 bytes January 1, 1 CE to December 31, 9999
Decimal System.Decimal 12 bytes +/-79,228,162,514,264,337,593,543,950,335 with no decimal point; +/-7.9228162514264337593543950335 with 28 places to the right of the decimal; smallest non-zero number is +/-0.0000000000000000000000000001
Double System.Double 8 bytes -1.79769313486231E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values
Integer System.Int32 4 bytes -2,147,483,648 to 2,147,483,647
UInteger System.UInt32 4 bytes 0 through 4,294,967,295 (unsigned)
Long System.Int64 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ULong System.UInt64 8 bytes 0 through 18,446,744,073,709,551,615 (1.8...E+19) (unsigned)
Object System.Object (class) 4 bytes Any type can be stored in a variable of type Object
Short System.Int16 2 bytes -32,768 to 32,767
UShort System.UInt16 2 bytes 0 through 65,535 (unsigned)
Single System.Single 4 bytes -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values
String System.String (class) 10 bytes + (2 * string length) 0 to approximately two billion Unicode characters
User-Defined Type (structure) (inherits from System.ValueType) Sum of the sizes of its members Each member of the structure has a range determined by its data type and independent of the ranges of the other members