VB.NET 2003 and 2005 snippets
18/11/2009 14:05Add 'all' Date/Time Formats to Listbox/Combobox
'Should add all of the available Date and Time formats to a combobox or listbox control.
Dim dateTime As DateTime = New _
DateTime(Now.Year, Now.Month, Now.Day, Now.Hour, _
Now.Minute, Now.Second)
Dim d() As String = Nothing
d = dateTime.GetDateTimeFormats()
ListBox.Items.AddRange(d)
top
Add all Known Colors to ComboBox/ListBox Control
Imports System.Drawing
Dim kColor As KnownColor
For kColor = KnownColor.AliceBlue To KnownColor.YellowGreen
cmbColor.Items.Add(kColor)
Next
top
Add 'all' Special-Folders to Listbox/Combobox
'Will add I think all special folders to a listbox or combobox.
Dim sFolder As Environment.SpecialFolder
For sFolder = 0 To 43
If Not Char.IsNumber(sFolder.ToString) Then
lst.Items.Add(sFolder.ToString)
End If
Next
top
Allow only Numbers in a Textbox Control
'Allow only numbers when someone types in a textbox control
'Add a textbox to the form and name is: txt . Then put the following
'code in the Key_Press event of the textbox control.
If e.KeyChar.IsNumber(e.KeyChar) = False Then
e.Handled = True
End If
top
AntiAlias Graphics
Imports System.Drawing.Drawing2D
'Just a example for your graphics variable. Change g to whatever your object variable is.
Dim g As Graphics
'Will smooth out all your lines, edges, corners, ect....
g.Graphics.SmoothingMode = SmoothingMode.AntiAlias
top
App.Previnstance Equivalent
'This uses the Process class to check for the name of the current applications process and see whether or not there are 'more than 1x instance loaded.
'This code is similar to Visual Basic 6.0's App.Previnstance feature.
Dim appName As String = Process.GetCurrentProcess.ProcessName
Dim sameProcessTotal As Integer = Process.GetProcessesByName(appName).Length
If sameProcessTotal > 1 Then
MessageBox.Show("A previous instance of this application is already open!", " App.PreInstance Detected!", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
Me.Close()
End If
appName = Nothing
sameProcessTotal = Nothing
top
Basic Error Handling
'This shows how to use the Try and Catch method for some error handling. Below is just some random code to test with.
Dim f As IO.File
Try
f.Open("D:\fileDoesNotExistFile.txt", IO.FileMode.Open) 'this will cause a file not found error to be thrown.
Catch exc As Exception
MessageBox.Show(exc.Message, " Error", MessageBoxButtons.OK, MessageBoxIcon.Error) 'This will give a description of the error.
End Try
top
Check for a specified String in a String
'
'Will check a string to see if it contains a specified string.
'
'The string that will be searched.
Dim str As String = "This string has some text"
'
'The string to find.
Dim i As Integer = str.IndexOf("string")
'
'If it returns -1 it means that no matches for the specified string was found.
If Not i = -1 Then
MessageBox.Show("Yeps, that string is in here!")
Else
MessageBox.Show("No, the string is not in here!")
End If
top
Check if Class/Object needs new instance or if its disposed, ect
'
'Check before getting the 'Object reference not set to an instance of an object' error
'message is going to been thrown! The code below will check if the variable to the
'Class/Object has been set to a instance of the object, disposed, ect.. - WITHOUT getting a
'error in your apps.
'
Dim audioObject As Microsoft.DirectX.AudioVideoPlayback.Audio
If audioObject Is Nothing Then
MessageBox.Show("This object is not usable yet! You need to set a new instance of the object!", _
" Not usable!", MessageBoxButtons.OK, MessageBoxIcon.Error)
'Now set a new instance of the object since you found out it was set!
audioObject = New Microsoft.DirectX.AudioVideoPlayback.Audio("c:\windows.wav")
Else
MessageBox.Show("This object is usable!", _
" It is Usable!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
top
Clear Drawing Surface
'Change e to whatever your graphics variable is.
'Change Black to whatever you want the color to be
e.Graphics.Clear(Color.Black)
top
Current Time and Date
MessageBox.Show(Date.Now)
top
Directory Exist
Imports System.IO
Dim dir As IO.Directory
MessageBox.Show(dir.Exists("c:\"))
top
Disable that 'Beep' in a Textbox control when pressing the Keyboards - 'Enter' Key
'
'This will disable that 'Beep' when you press the 'Enter' key in a Textbox control. You want to
'put this code in the TextBox_KeyPress event of your Textbox.
'
'You can use the 'Carriage Return Character' constant: 'vbCr' as the KeyChar to check or you can
'simply use: Chr(13). The end result is the same.
'
If e.KeyChar = Chr(13) Then
e.Handled = True
End If
'
'or using the constant as the KeyChar below:
'
If e.KeyChar = vbCr Then
e.Handled = True
End If
top
Doevents in VB.Net
System.Windows.Forms.Application.DoEvents()
top
Download File From the Internet
Dim wClient As Net.WebClient = New Net.WebClient
'the web address to the file to download.
Dim theAddy As String = "https://www.vbcodesource.com/dummyFile.txt"
'the file to download and the file to save the downloaded file too.
wClient.DownloadFile(theAddy, "c:\dummy.txt")
top
Draw Gradient on Form
'In the Form_Paint event. Put the following code
Dim rec As Rectangle = New Rectangle(0, 0, Me.Width, Me.Height) 'create a new recatangle
'Create a new brush. Make is a Gradient style brush.
Dim myBrush As Brush = New Drawing.Drawing2D.LinearGradientBrush(rec, Color.Aqua, Color.Yellow, _
Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal)
'draw the gradient onto the form.
e.Graphics.FillRectangle(myBrush, rec)
top
Draw a Line on a WindowsForm
'Draw line on form
Dim bit As Bitmap = New Bitmap(Me.Width, Me.Height)
Dim g As Graphics = Graphics.FromImage(bit)
Dim myPen As Pen = New Pen(Color.Blue, 3)
Me.CreateGraphics.DrawLine(myPen, 0, 0, Me.Width, Me.Height)
top
Draw a Line on a Picturebox Control
'Draw line on picturebox
'Put a picturebox on the form named pic
Dim bit As Bitmap = New Bitmap(pic.Width, pic.Height)
Dim g As Graphics = Graphics.FromImage(bit)
Dim myPen As Pen = New Pen(Color.Blue, 3)
g.DrawLine(myPen, 0, 0, pic.Width, pic.Height)
pic.Image = bit
top
Draw String on Form
'create a new brush with a single, solid color
Dim myBrush As New SolidBrush(Color.Purple)
'create a new basic font. you can mess around and make it cooler
Dim f As Font = New Font(Font.Bold, 20)
'draw the string onto the form. At Position (0 left), (10 top)
Me.CreateGraphics.DrawString("Hello, This is just a test!", f, myBrush, 0, 10)
top
File Exist
Dim f As IO.File
MessageBox.Show(f.Exists("d:\someFileName.txt"))
top
Find/Search for a String in a Listbox/Combobox control
'
'txtItem.Text would be a textbox control whose text will be searched. And of
'course, lstItems is a Listbox control or you can make it a Combobox control. The code below
'shows searching for a partial/exact string at either the beginning of the control or at a
'specified Index value.
'
'
'Search a Listbox Control for a exact string
lstItems.SelectedIndex = lstItems.FindStringExact(txtItem.Text)
'
'Search a Listbox Control for a partial string
lstItems.SelectedIndex = lstItems.FindString(txtItem.Text)
'
'Start searching a Listbox Control for a partial string at Index value 4.
lstItems.SelectedIndex = lstItems.FindString(txtItem.Text, 4)
'
'Start searching a Listbox Control for a exact string at Index value 2.
lstItems.SelectedIndex = lstItems.FindStringExact(txtItem.Text, 2)
top
Generate Random Numbers
'Instantiate the random class
Dim r As Random = New Random
'
'Get a random number within the full range of a integer value.
MsgBox(r.Next())
'
'Generates a random number from 0 up to the set maximum. It is
'set not to return a number larger than 20.
MsgBox(r.Next(20))
'
'Generates a random number within the minumum and maximum
'numbers that are specified. IT will not return a number lower
'than the setMinumum, or return a number higher than the setMax.
MsgBox(r.Next(10, 15))
top
Get a List of 'all' available Fonts
'This will get all of the available fonts on the computer and add
'them to the 'cmbFont' combobox control.
Dim f As System.Drawing.Text.InstalledFontCollection = New _
System.Drawing.Text.InstalledFontCollection
Dim fFamily As FontFamily
For Each fFamily In f.Families
lst.Items.Add(fFamily.Name)
Next
top
Get the Application Path WITHOUT the Filename
Dim appPath As String
appPath = System.Windows.Forms.Application.StartupPath
MessageBox.Show(appPath)
top
Get the Application Path with the Filename
Dim appPathFilename As String
appPathFilename = System.Windows.Forms.Application.ExecutablePath
MessageBox.Show(appPathFilename)
top
Messageboxes with Multiple Lines
'Simply uses the vbNewLine constant that will make it VERY easy to create multi-line messageboxes.
'
'Get a random number within the full range of a integer value.
MessageBox.Show("This IS a multiline messagebox!" & vbNewLine & vbNewLine & _
"See!, I told you so :)", " Multiline Messagebox!", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
top
Open a URL/Webpage in the Default Web Browser
'
'Simply opens the default web browser and navigate to the specified url.
'
Dim webAddress As String = "https://www.vbcodesource.com"
Process.Start(webAddress)
top
Read Contents of a Text File and Add to a Textbox Control With Stream Reader Class
'Read from a text file to a textbox with the Stream Reader Class
'Put a textbox on the form and name txt and set to multi-line
'Make the Reader read the entire contents of the textfile and write to the textbox
'Add to text file
Dim sReader As IO.StreamReader = New IO.StreamReader("c:\newTextFile.txt")
'Make the textbox keep the current data while adding the new data
txt.AppendText(sReader.ReadToEnd)
top
Time/Pause for the Specified Time
'This will pause or timeout your applications code for the specified amount of milli-seconds.
'
'Declare a new DateTime variable and fill it with the current
'time with 2000 milli-seconds added to it.
Dim timeOut As DateTime = Now.AddMilliseconds(2000)
Do
'
'Keep the app from freezing and allow Windows to continue processing the applications messages.
Application.DoEvents()
'Keep looping until the elasped time of 2000 milliseconds.
Loop Until Now > timeOut
MsgBox("The code paused for: 2000 Milli-Seconds or 2 Seconds!")
top
Write Text to a Text File with Stream Writer Class
'Write to text file with the Stream Writer Class
Dim sWriter As IO.StreamWriter = New IO.StreamWriter("c:\newTextFile.txt")
'This is pretty much easy to understand. No explanation
sWriter.WriteLine("Hi")
sWriter.WriteLine("Testing out this code")
sWriter.WriteLine("Hopefully this code will work")
sWriter.WriteLine("Lets flush the stream and see")
'Put the data inside the text file
sWriter.Flush()
top
Visual Basic.NET 2005 Snippets
Add all Date and Time formats to Listbox/Combobox Add all Special Folders to Listbox/Combobox Check if a String contains a specified String Check if your Class/Object needs a new instance or is disposed Check if a File or Directory Exists Check if the Computer is Connected to the Network Clear the Windows Clipboard Copy, Create, Delete, and Rename a Directory Copy and Paste (Get/Set) Text to the Clipboard Disable that 'Beep' in the Textbox control when pressing the 'Enter' Key. [Method #1] Disable that 'Beep' in the Textbox control when pressing the 'Enter' Key. [Method #2] DoEvents_Sub Routine DoEvents_Sub Routine WITH the - 'GetInputState' - API Call
Download File from Internet to Hard Drive Generate Random Numbers Get a list of available Fonts Get the Computers Display Resolution Get the Amount of Free(Available) Physical and Virtual Memory Get the Computers Total Physical (Ram) and Virtual Memory Get the Operating Systems - Full Name, Platform, and Version Messageboxes with Multiple Lines Only allow Numbers in a TextBox Control Open a Webpage/Url with the default Webbrowser Ping the specified Url/Address Play/Stop a Specified Wave File and System Sound Timeout or Pause for a specified time
Add all Date and Time formats to listbox or combobox.
'Should add all of the available Date and Time formats to a combobox or listbox control.
Dim dateTime As DateTime = New _
DateTime(Now.Year, Now.Month, Now.Day, Now.Hour, _
Now.Minute, Now.Second)
Dim d() As String = Nothing
d = dateTime.GetDateTimeFormats()
ListBox1.Items.AddRange(d)
top
Add special folders to listbox or combobox
'Will add I think all special folders to a listbox or combobox.
Dim sFolder As Environment.SpecialFolder
For sFolder = 0 To 43
If Not Char.IsNumber(sFolder.ToString) Then
lst.Items.Add(sFolder.ToString)
End If
Next
top
Check if a String contains a specified String
'Check if a String contains a specified string.
'
Dim str As String = "This string has some text"
If str.Contains("string") Then
MessageBox.Show("Yeps, that string is in here!")
Else
MessageBox.Show("No, the string is not in here!")
End If
top
Check if a Specified File or Directory Exists
'
'Check whether a File or Directory exists.
'
MsgBox(IO.File.Exists("c:\theFile.txt"))
MsgBox(My.Computer.FileSystem.DirectoryExists("c:\"))
top
Check if the Computer is Connected to a Network
'
'Check if the computer is connected to the network.
'
MsgBox(My.Computer.Network.IsAvailable)
top
Check if your Class/Object variable needs a new instance or if disposed
'
'Check before getting the 'Object reference not set to an instance of an object' error
'message is going to been thrown! The code below will check if the variable to the
'Class/Object has been set to a instance of the object, disposed, ect.. - WITHOUT getting a
'error in your apps.
'
Dim audioObject As Microsoft.DirectX.AudioVideoPlayback.Audio
If audioObject Is Nothing Then
MessageBox.Show("This object is not usable yet! You need to set a new instance of the object!", _
" Not usable!", MessageBoxButtons.OK, MessageBoxIcon.Error)
'Now set a new instance of the object since you found out it was nothing!
audioObject = New Microsoft.DirectX.AudioVideoPlayback.Audio("c:\windows.wav")
Else
MessageBox.Show("This object is usable!", _
" It is Usable!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
top
Clear the Windows Clipboard
'
'Clear the Windows Clipboard.
'
My.Computer.Clipboard.Clear()
top
Copy and Paste (Get/Set) Text to the Windows Clipboard
'
'Get/Set(Copy/Paste) text to the Windows Clipboard.
'
My.Computer.Clipboard.SetText("This is my text", TextDataFormat.Text)
MsgBox(My.Computer.Clipboard.GetText(TextDataFormat.Text))
top
Copy, Create, Delete, and Rename a Specified Directory
'
'Copy, Create, Delete, and Renaming a Directory.
'
Dim dir As String = "c:\Directory"
'
'Create a directory with the path and name specified in the dir string variable.
My.Computer.FileSystem.CreateDirectory(dir)
'
'New directory with the contents of the dir path copied to it.
My.Computer.FileSystem.CopyDirectory(dir, "c:\Directory Copied")
'
'Rename the original directory that is specified in the dir variable to the new directory name.
My.Computer.FileSystem.RenameDirectory(dir, "Directory Renamed")
'
'Delete both the Copy Directory and the Renamed Directory from the harddrive.
My.Computer.FileSystem.DeleteDirectory("c:\Directory Copied", FileIO.DeleteDirectoryOption.DeleteAllContents)
My.Computer.FileSystem.DeleteDirectory("Directory Renamed", FileIO.UIOption.AllDialogs, FileIO.RecycleOption.SendToRecycleBin, FileIO.UICancelOption.DoNothing)
top
Disable that 'Beep' in the Textbox control when pressing the 'Enter' Key. [Method #1]
'
'This code will disable the 'Beeping' you get when you press the 'Enter' key in a Textbox
'control. This code needs to go into the 'Textbox_KeyDown' event.
'
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
End If
top
Disable that 'Beep' in the Textbox control when pressing the 'Enter' Key. [Method #2]
'
'This code will disable the 'Beeping' you get when you press the 'Enter' key in a Textbox
'control. This code needs to go into the 'Textbox_KeyPress' event. You can use Chr(13) or the
'constant 'vbCr' as the Keychar.
'
If e.KeyChar = Chr(13) Then
e.Handled = True
End If
'
'or using the KeyChar below:
'
If e.KeyChar = vbCr Then
e.Handled = True
End If
top
DoEvents_Sub Routine
'This will process all messages that are queued up. Doevents()
'will keep your application from appearing frozen to the user
'while your loops or whatever code is processing. If you are
'going to use long loops or code where you will be needing to
'use DoEvents() for a extended period of time, I highly
'recommend you use the GetInputState() Api Call instead of
'allowing the application to continuously call DoEvents(). Your
'application will gain LOTS of speed by using GetInputState()
'and it will NOT freeze on the user, thus still allowing them
'to interact with your application.
Application.DoEvents()
top
DoEvents_Sub Routine WITH the - 'GetInputState' - API Call
'This will use GetInputState() to check whether there are
'any messages that needs to be processed and THEN it will
'call DoEvents() to process the messages. As a result, the
'code will be MANY times faster than if you used DoEvents()
'by itself.
'
'Add this API call to the Declaration section of your application.
Private Declare Function GetInputState Lib "user32" () As Integer
Do
'
'Checks if any messages are queued up before DoEvents()
'If there ARE messages that needs to be processed, THEN
'it will call DoEvents() and let the messages go ahead
'and process.
'
If GetInputState <> 0 Then Application.DoEvents()
Loop Until Me.Text = "Done"
top
Download a File from the Internet to the Hard Drive
'
'Download a specified file from the internet and put it in the specified directory.
'
My.Computer.Network.DownloadFile("https://www.webAdress.com/page.html", "c:\thePage.html")
top
Generate random numbers
'Instantiate the random class
Dim r As Random = New Random
'
'Get a random number within the full range of a integer value.
MsgBox(r.Next())
'
'Generates a random number from 0 up to the set maximum. It is
'set not to return a number larger than 20.
MsgBox(r.Next(20))
'
'Generates a random number within the minumum and maximum
'numbers that are specified. IT will not return a number lower
'than the setMinumum, or return a number higher than the setMax.
MsgBox(r.Next(10, 15))
top
Get a list of available Fonts
'This will get all of the available fonts on the computer and add
'them to the 'cmbFont' combobox control.
Dim f As System.Drawing.Text.InstalledFontCollection = New System.Drawing.Text.InstalledFontCollection
Dim fFamily As FontFamily
For Each fFamily In f.Families
lst.Items.Add(fFamily.Name)
Next
top
Get the Amount of Free (Available) Physical (Ram) and Virual Memory
'
'Get the amount of Physical and Virtual Memory that is available.
'
MsgBox(" Available Physical Memory: " & My.Computer.Info.AvailablePhysicalMemory.ToString & " bytes")
MsgBox(" Available Virtual Memory: " & My.Computer.Info.AvailableVirtualMemory.ToString & " bytes")
top
Get the Operating Systems - Full Name, Platform, and Version
'
'This will throw 3x messageboxes with the FullName of the Installed Windows, along with the OS
'Platform, and OS Version that your program is running on.
'
MsgBox(My.Computer.Info.OSFullName)
MsgBox(My.Computer.Info.OSPlatform.ToString)
MsgBox(My.Computer.Info.OSVersion.ToString)
top
Get the Total Amount of Installed Physical (Ram) and Virual Memory for the Computer
'
'Returns the total amount of Physical and Virtual Memory for the Computer.
'
MsgBox(" Total Physical Memory: " & My.Computer.Info.TotalPhysicalMemory.ToString & " bytes")
MsgBox(" Total Virtual Memory: " & My.Computer.Info.TotalVirtualMemory.ToString & " bytes")
top
Get the Computers Display Resolution
'
'Get the displays current Resolution.
'
MsgBox("Resolution is: " & My.Computer.Screen.Bounds.Width.ToString & "x" & My.Computer.Screen.Bounds.Height.ToString & " Pixels")
top
Messageboxes with Multiple Lines
'Simply uses the vbNewLine constant that will make it VERY easy to create multi-line messageboxes.
'
'Get a random number within the full range of a integer value.
'
MessageBox.Show("This IS a multiline messagebox!" & vbNewLine & vbNewLine & "See!, I told you so :)", _
" Multiline Messagebox!", MessageBoxButtons.OK, MessageBoxIcon.Information)
top
Only allow Numbers in a TextBox Control
'
'This will simply check the Keychar that was pressed and will only allow numbers to be typed
'in the TextBox control. Put in the 'TextBox_KeyPress' event.
'
If Not Char.IsNumber(e.KeyChar) Then
e.Handled = True
End If
top
Open a URL with the Default WebBrowser
'
'Simply opens the default web browser and have it goto the specified url.
'
Dim webAddress As String = "https://www.vbcodesource.com"
Process.Start(webAddress)
top
Ping the Specified Url/Address
'
'Ping a url that is specified in the parameter.
'
MsgBox(My.Computer.Network.Ping("www.vbcodesource.com").ToString)
top
Play and Stop a Specified Wave File and System Sound
'
'This will Play a Wave file from the specified Path, Play a selected system Sound and Stop a
'sound that is playing.
'
My.Computer.Audio.Play("C:\WINDOWS\Media\Windows XP Default.wav", AudioPlayMode.Background)
My.Computer.Audio.PlaySystemSound(Media.SystemSounds.Beep)
My.Computer.Audio.Stop()
top
Timeout or Pause for a specified time
'This will pause or timeout your applications code for the specified amount of milli-seconds.
'
'Declare a new DateTime variable and fill it with the current
'time with 2000 milli-seconds added to it.
'
Dim timeOut As DateTime = Now.AddMilliseconds(2000)
Do
'
'Keep the app from freezing.
Application.DoEvents()
'Keep looping until the elasped time of 2000 milliseconds.
Loop Until Now > timeOut
MsgBox("The code paused for: 2000 Milli-Seconds or 2 Seconds!")
———
Back