Visual Basic .net
<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
Contents
- 1 Application
- 2 Graphics
- 2.1 Simple pixel plotting
- 2.2 Setting up graphics and drawing pixels, shapes, and colours
- 2.3 Copies bitmap named bm into a 1D array called picArray as A,R,G,B,A,R,G,B,...
- 2.4 Clearing the bitmap to a solid colour
- 2.5 Loading an image file into a picture box
- 2.6 Saving a picture box to an image file
- 2.7 Reading the mouse position within a picture box
- 2.8 Drawing text on a bitmap (and then into a picture box)
- 3 Files
- 3.1 Reading text files line by line
- 3.2 Writing text the preferred way (simpler and faster)
- 3.3 Writing text files line by line
- 3.4 loading data files into an array of bytes
- 3.5 Writing binary files
- 3.6 Using a "Browse" button
- 3.7 Adding file paths to an array, from a directory
- 3.8 Reading XML files
- 4 Arrays
- 5 Threading / Parallel
- 6 Loops
- 7 Conditionals
- 8 Math
- 9 Calling Windows API
- 10 RS-232
- 11 Network / Internet
- 12 Conversion
- 13 Strings
- 13.1 Finding text in a string
- 13.2 Using the start of a string
- 13.3 Using the middle of a string
- 13.4 Using the end of a string
- 13.5 Getting just the path of a file given the entire path and filename as a string
- 13.6 Getting just the file name (with extension) of a file given the entire path and filename as a string
- 13.7 Getting just the file name (without extension) of a file given the entire path and filename as a string
- 13.8 Seperating the values from a time and date string
- 13.9 Converting a string to a number in other locales
- 14 Time
- 15 Multimedia
- 16 Datatypes
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
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) 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) 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 A,R,G,B,A,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, Imaging.PixelFormat.Format32bppArgb, Imaging.PixelFormat.Format32bppPArgb, Imaging.PixelFormat.Format32bppRgb '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.Format32bppArgb) 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
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) BW.Write(byteval) 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
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
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 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
Step size must be negative for down counting loops
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
Case
Select Case i Case 0 'this code will run if i=0 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 Else 'this code will run if i didn't match any of the above cases End Select
Math
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
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")
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()
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
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)
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 |