How to Play Two Audio Files at the Same Time in VB 6.0 and VB.NET

How you can easily Play 2 or more Audio files Simultaneously using Visual Basic 6.0 and Visual Basic.NET

This article will be using the MCISendString function via the ‘winmm.dll’ library to control the playback and properties of multiple audio files independently from one another. You can mix and match file types like .mp3, .wav, .wma, and .midi files or clips as well.

If you’ve never worked with the Windows Multimedia Command Interface before I suggest you check out my beginner tutorial at this link for an easy step by step guide. It should get you started with a good understanding of the basics on sending Command Strings with the MCISendString function.

Note: The .NET code in this article is compatible with the original versions as well as the 2005, 2008, VB 2010, and newer versions.

Continue reading

Visual Studio Community 2013 and Visual Studio 2015 Preview

Update Edit: Dec 12th 2014: Just wanted to mention that Microsoft has recently released a video about the Community Edition of Visual Studio 2013. You can watch the video by clicking here.


Microsoft has announced two new releases or additions to their Visual Studio.NET platform. A preview version of Visual Studio 2015, and a new ‘Community Edition’ of VS 2013 ready for downloading. I am personally interested in the 2013 Community version of VB. I usually use the Express Edition of Visual Basic 2010 for most things and would like a couple features not available with VB 2010 Express.

So, is Visual Studio Community 2013 just mildly enhanced Express Editions? Nope, not at all. In fact, you can think of it as Visual Studio 2013 Professional Edition according to Microsoft. A huge part of Pro over Express that I desired was the support for Add-ins/Extensions. There are literally thousands of extensions available including many being completely Free. You can check out the extensions by clicking here

Continue reading

Free Visual Basic Icons and Image Resources! | Updated

Free VB and Visual Basic.NET icons for your programs and applications!

Icons or Images can really enhance your Visual Basic 6.0 and Visual Basic.NET applications. Unfortunately a lot of the Icons you find either cost money and/or will not allow you to use them in a commercial application. So that is where this little post comes in. I have sources below that’s either free for all uses or free for non-commercial.  I will continue to add sources as they are found. Leave a comment if you have another good source to add here.

Note: While VB 6.0 and VB.NET may come with icons, you may want something a little newer or more unique. That’s why I made this post.

Starting below are sources for free VB 6.0 Icons and Visual Basic .NET icons

Continue reading

Sending SMTP Email with Advanced Features in Visual Basic.NET | Part 2 – Include Alternate eMail Views

This is Part 2 of the Sending Email using SMTP with Advanced Features series. The first series went over how to add multiple attachments to an email message for someone to download when they view your email. I suggest you check that article out at this web link. Also for the basics of sending Smtp emails you really should check out the article here.

This article will show how to send your email message with Alternative Views. For instance, you can send an HTML based email message and also include a Plain Text Only version in the same email. This can help ensure that the recipient(s) can view your email in case the email provider or client software only supports Text based emails and so on. All you need to do is make your html based message and the plain text only message, then add those views to the email message using the AlternateView class.

Note: I do want to mention that these series of articles only work with Visual Basic 2005, VB 2008, Visual Basic 2010 and Higher since I am using the class libraries under the System.NET.Mail namespace, which wasn’t added until .NET Framework 2.0 and higher which of course includes version 3.5, DotNet 4.0, and newer.

First of all to get started you will want an instance of a couple classes. I am using the same gmail based codes I used in the first advanced article for this series.

  • System.Net.Mail.SmtpClient
  • System.Net.Mail.MailMessage

Continue reading

Advanced Textbox Manipulation in Visual Basic and VB.NET | Part 2

This is Part Two of the Advanced Textbox Control Manipulation series. If you haven’t already you should check out Part 1 of this series. That article showed how to use the SendMessage API call to make a Textbox control Page Left, Page Right, Line Left, Line Right, Left Edge, and go to the Right Edge of the contents. This Part 2 post will show how to add the functionality that is outlined below…

Page UP

Page Down

Line UP

Line Down

Top Edge

Bottom Edge

Note: These codes are basically taken from an example I for VB.NET that shows lots and lots of various textbox based manipulating and functionality. Just go to http://www.vbcodesource.com under the Visual Basic.NET – Examples page.

Continue reading

Sending SMTP Email with Advanced Features in Visual Basic.NET | Part 1 – Adding Multiple Attachments

This is Part 1 of ‘Sending Email with Advanced Features’ which will show how you can send an email message and add not just one attachment, but pretty much as many attachments as you want. If you haven’t already, I recommend you check out this article I made on the basics of setting up and sending email using the System.NET.Mail SMTP feature in the DotNET Framework. The code I’m using is compatible with Visual Basic .NET 2005, VB 2008, and VB.NET 2010 since I’m using the classes under the System.NET.Mail namespace which is made available in the .NET 2.0, .NET 3.0, .NET 3.5, and the .NET 4.0 Frameworks. I am using SMTP and a Google GMail account to send the email message.

First of all to get started you will want a instance of a few classes. Below are the ones you’ll need to setup…

  • System.Net.Mail.SmtpClient
  • System.Net.Mail.MailMessage
  • System.Net.Mail.Attachment

Below are the variables I am using for the classes above..

Continue reading

How to Play an Embedded Resource .Wave Sound in VB.NET 2008, Visual Basic 2010, and Newer

I’ve recenty been making an example program with Visual Basic.NET 2008 on snapping forms to the edge of the screen. I wanted the program to play a sound wave file when it performed the snapping process. But I didn’t want to have to make it link to external wave files or anything. So I decided to embed the wave sound bytes in the program itself. So this little article will show you how I went about doing that. Here is a link to the actual example application that this article is based on.

Example Playing Embedded Wave Sounds


More Info

The first thing you want to do of course is determine the wave files you want to play in your application. Remember that the size of each .wav file in bytes, willl be added to your programs file size. So remember that when you decide on what sound files you want to use.

I also want to mention that this article is specific to VB .NET 2005/2008/2010 and higher since I am using the SoundPlayer class. Visual Basic .NET 2002/2003 will have to use the PlaySound api thats part of the WinMM.dll library. The PlaySound api can play and do everything the SoundPlayer class in VB 2005 and higher can do. Just more code is involved. I actually found an article after I started this post that shows how to play wave files embedded in your VB.NET 02/03 application. Just click here to check it out.

Embedding your .Wave Files

After you have determined the wave files you want to embed in your program you need to add them to your project. There are a couple ways to do this. The easiest way is to copy your .wav file and then paste it in your project. To paste it to your project you just need to select your project name in the Solution Explorer, usually the top right panel. Then right click and click on the paste command. Another way is to click on the “Project” and click on “Add Existing Item”. Then just browse to the wave files location and select each file you want to embed. Once the files are added to your project, you will want to click on each wave file and in the properties panel (Its right below the Solution Explorer by Default). In the Properties panel you will see “Build Action”. From the build action combo list select “Embedded Resource”. Do that for each sound file you added to your project.

Playing your Embedded Files

Now that you have embedded your files into your application, its time to setup the code to play them. If your using .NET older than 2005 then check out this article on using the unManaged api call “PlaySound” to do the playback.

You now need to access your newly embedded *.wav file. You can access it as a stream under your programs manifest. Here is the method that will be used…

Public Overridable Function GetManifestResourceStream(ByVal name As String) As System.IO.Stream Continue reading

Performing Various Listview Control Tasks in VB.NET | Part 2 – Sorting and Shuffling or Randomizing Items

Part Two on performing various Listview Control tasks for Visual Basic.NET, VB 2008, Visual Basic 2010, and VB 2013.

The listview control has been available to VBers since the classic days. VB.NET continues with its version of the listview control as well. The control can provide VERY user-friendly features to your program. You can add Groups, Columns, and more with various display preferences like Icons and Details. The purpose of this post is simply to give you some basic code that i’ve learned/used over time for the Listview Control.

Note: These codes should have no problems working with Visual Basic.NET 2008, and Visual Basic 2010. For this article I am calling my Listview control’s name: Listview1. So all of the code will be using that name when referring to the listview object. I also set the controls ‘View’ property to: “Details” and added 2 columns.


Sorting Items…

I have a few tasks to show related to item based sorting. I will show how to Sort the Listviews item contents by Name, using Ascending and Descending styles. I want to show how to shuffle or randomize (or is it randomise?)  the items in a listview control. I will also show how to allow the user to click on one of the listviews columns to sort items both Asending and Desending,

Sorting Items – Ascending

            Listview1.Sorting = SortOrder.Ascending

Sorting Items – Descending

            Listview1.Sorting = SortOrder.Descending

Sorting Items – None (No Sorting at All)

            Listview1.Sorting = SortOrder.None

Shuffling, or Randomizing Items…

This source code will randomly sort all of the items in the listview control. There may be a more efficient way for this, but this code does work.

        '
        'This will go through the list contents and reorder the items randomly.
        '
        Dim r As New Random
        Dim item As ListViewItem
        Dim index As Integer
        '
        'You first need to set sorting to None.
        Listview1.Sorting = SortOrder.None
        '
        'Now go through the contents of the list.
        For i As Integer = 0 To Listview1.Items.Count - 1
            '
            'Get a randon number to use as the index to insert the item again.
            index = r.Next(i, Listview1.Items.Count)
            '
            'Set to each item in the list.
            item = Listview1.Items.Item(i)
            '
            'First remove that item.
            Listview1.Items.Remove(item)
            '
            'Then insert that item using the new random index number.
            Listview1.Items.Insert(index, item)

        Next

Sorting Items with a Column Click

OK, this last bit of code will sort the items when a user clicks on the column. You just need to make minor changes to the code below, depending on which column in the Index you want to activate the sorting process. The code Has to go in the Listview controls _ColumnClicked event.

    Private Sub Listview1_ColumnClick(ByVal sender As Object, ByVal e As System.Windows.Forms.ColumnClickEventArgs) Handles Listview1.ColumnClick
        '
        'These codes will check which sorting style is enabled and will either set to Ascending or Descending.
        'e.Column is the Index of the column that was clicked. I check for the first Column only which is 0 (Zero).
        '
        If e.Column = 0 AndAlso Listview1.Sorting = SortOrder.Descending OrElse Listview1.Sorting = SortOrder.None Then

            Listview1.Sorting = SortOrder.Ascending

        ElseIf e.Column = 0 AndAlso Listview1.Sorting = SortOrder.Ascending Then

            Listview1.Sorting = SortOrder.None

        End If

    End Sub

You see that it really is easy to do all of these tasks. I don’t exactly like the code I made on shuffling/randomizing the items but it works. Just not sure how good the performance would be with a thousand items listed. I haven’t decided yet on what to do for the next Listview Control article. Feel Free to leave a comment if you have something in mind.  Have fun!

Jason

Minor Revision: 2015

Performing Various Listview Control Tasks in VB.NET | Part 1 – Removing Items

Part One on performing various Listview Tasks using VB.NET, VB 2008, VB 2010, and Visual Basic 2013.

The listview control has been available to VBers since the classic days. VB.NET  continues with its version of the listview control as well. The control can provide user-friendly listing features to your programs. You can add Groups, Columns, and more with various display preferences like Icons and Details. The purpose of this post is simply to give you some basic code that i’ve had to use over time for removing items from the Listview Control.

Note: These codes should have no problems working with Visual Basic.NET 2008, Visual Basic 2010, and newer. For this article I am calling my Listview control’s name: Listview1. So all of the code will be using that name when referring to the listview object. I also set the controls ‘View’ property to: “Details” and added 2 columns.


Removing/Deleting Listview Items…

I have three tasks related to item removal. Removing All, Remove Checkmarked, and Remove the Selected items. Once you have a basic understanding of the component these task are quite easy. It actually takes very little code.

 

Remove – All Items

        Listview1.Items.Clear()

 

Remove – Checkmarked Items Only

        For item As Integer = 0 To Listview1.CheckedItems.Count - 1

            Listview1.CheckedItems(0).Remove()

        Next

OR

        Do While Listview1.CheckedItems.Count > 0

            Listview1.CheckedItems(0).Remove()

        Loop

 

Remove – Selected Items Only

        For item As Integer = 0 To Listview1.SelectedItems.Count - 1

            Listview1.SelectedItems(0).Remove()

        Next

OR

        Do While Listview1.SelectedItems.Count > 0

            Listview1.SelectedItems(0).Remove()

        Loop

Thats all there is to it! If I come up with more ways or come across any other codes related to removing items then I will update this post. In the next article I plan on showing how to Sort items in the Listview control and Shuffle, or Randomize the contents/items of the Listview control. Have fun!

Jason

Minor Revision: 2015

Getting the Computers Windows Directory using VB and Visual Basic.NET

This little article will show you how to get the Windows directory/folder using both classic vb and vb.net. For some reason Microsoft didn’t add built-in support for getting the path of the users windows directory until .NET 4.0. It is located under the: Environment.SpecialFolders feature. Otherwise I will show a way to get the windows path in the earlier versions of VB.NET and a way to get the directory path using VB 6.0 and Visual Basic.NET.


Both VB6.0 and Visual Basic NET

This is a simple API call that will give you the windows installed directory for the computer. You just need to create a string buffer and the api function will set the information you want in that buffer.

'Visual Basic 6.0 Declare

  Private Declare Function GetWindowsDirectory Lib "kernel32" Alias "GetWindowsDirectoryA" (ByVal lpBuffer As String, ByVal nSize As Long) As Long
'Visual Basic.NET Declare

 Private Declare Function GetWindowsDirectory Lib "kernel32" Alias "GetWindowsDirectoryA" (ByVal lpBuffer As String, ByVal nSize As Int32) As Int32

Remaining code for API Method for All VB’s below…

'For both VB and VB.NET. This variable is for receiving the path from the API call.

    Dim winDir As String

 'Create a simple string buffer that will be passed to the api call to receive the directory for windows.

     winDir = Space$(255)

  'The winDir variable will get the value from the api call.

      GetWindowsDirectory winDir, Len(winDir)

'Trim the end of the value to remove the unused whitespaces from the string buffer.

      winDir = RTrim(winDir)

'This should throw a message box displaying the windows directory for the target computer.

    MsgBox(winDir)

When executing the code above, you should get a messagebox with the target computers Windows directory. It could be something similar to: “C:\Windows”


.NET based only using MY. below

Like I mentioned earlier Microsoft failed to include the Windows Directory as a Special Folder until .NET 4.0. But there is a another easy way to do it if you don’t want to use the API method.

This first way will actually use the Special Folder feature in .NET but will target the Environment.SystemDirectory. Since the System32 directory is always located under the base windows folder all you have to do is get the parent path of the SystemDirectory.

 MsgBox(My.Computer.FileSystem.GetParentPath(Environment.SystemDirectory))

The code above will throw a message with the parent path for the System32 directory. In my case is returned ‘c:\Windows’ just like the API version did.


There are other ways to get the windows direcory like checking a environment variable that I might add later on. The API version works great for both VB 6.0 and VB.NET, and the System32 method works just fine for .NET.  Remember Microsoft included the WindowsDirectory as a SpecialFolder in Visual Basic 2010 so you should use that method if possible. Anyways, thats all!

         Jason

Revised: 2015

Hide/Show the Cursor’s Caret using VB and VB.NET

There may be times when you don’t want your textbox or combobox to show the cursor’s caret position (blinking cursor). Thanks to a couple API calls, its easy to both hide and show the caret from the user. Microsoft made available the HideCaret and ShowCaret api functions.

I want to explain alittle more how the functions operate. Whenever you want to hide the caret using the HideCaret api call, say on one of your textbox controls, the target textbox needs to have ownership of the caret at the time the Hide Caret function is executed. Whenever the textbox loses ownership of the caret it will be reset back to the default setting. For example you call the HideCaret function which successfully hides the blinking cursor in the target textbox control. You then click on a button or another control that gets focus/ownership of the caret, then the caret/blinking cursor will be shown again in the target textbox when the user clicks or gives focus to the target textbox again. In other words, whenever ownership of the caret changes from one control to another then the Caret will reset back to its default setting. So, if you want the caret to always remain hidden from the user in your textbox, then you can do a simple trick to keep the blinking cursor from being shown even when it changes ownership.


First of all, you need to get the code for the two API calls…

VB.NET

Private Declare Function HideCaret Lib “user32? (ByVal wHandle As Int32) As Int32

Private Declare Function ShowCaret Lib “user32? (ByVal wHandle As Int32) As Int32

VB 6.0

Private Declare Function HideCaret Lib “user32? (ByVal wHandle As Long) As Long

Private Declare Function ShowCaret Lib “user32? (ByVal wHandle As Long) As Long

The functions are easy to use. All you have to do is call the two functions with the handle of the control whose caret you want to hide or show in the wHandle parameter like below…

VB.NET

    HideCaret(TextBox1.Handle.ToInt32)

    ShowCaret(TextBox1.Handle.ToInt32)

VB 6.0

    HideCaret Text1.hWnd

    ShowCaret Text1.hWnd

The codes above set to Hide/Show the caret in a textbox control.


If you want the cursor to never be shown in a textbox control, then simply put the HideCaret code in the Textbox_GotFocus() event. Like below…

VB.NET

Private Sub TextBox1_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus

HideCaret(TextBox1.Handle.ToInt32)

End Sub

VB 6.0

Private Sub Text1_GotFocus()

    HideCaret(Text1.hWnd) 

End Sub

With the code above, now each time the textbox control gets focus and ownership of the caret it will automatically call the HideCaret function. Thus the user should never see the blinking cursor at all.


That’s all for this tip I guess. 🙂

Jason

Minor Revision: 2015

Check if Windows or your Program is in 64-bit or 32-bit Mode using VB.NET and Higher

A while back I made a simple post on using WMI (Windows Management Instrumentaion) to check if the operating system your program was running on was 32-bit or 64-bit. The main problem with that method is its not supported on Windows XP and doesn’t tell you what mode your application is running in. I made a small example with different methods that should be near fool proof. I have 4 methods of checking if your application is 32 bit (x86) or 64 bit (x64 or AMD64 which is the code name). I also have 5 methods of checking what mode the operating system is running in. If you still can’t pin down whether your application/operating system is 32 or 64 bit then I don’t know what to tell you. BTW here is a link to the earlier post I made on how to easily check if the operating system is 32-bit or 64-bit using WMI, which applications running on Vista or Windows 7 can use just fine.

Image of example application

There is to much code in the example I made to post here. You should definitely download it and check it out. It was made with VB 2005 but the codes will work in VB.NET 2002,.NET 2003, Visual Basic 2008, and Visual Basic.NET 2010 as well. So I will just highlight a couple ways to determine your application and os mode.


The code below grabs a string from a registry key and examines the text. This  is pretty much a fool proof way of whether your cpu is running on a x86 or x64 operating system. All you need to do is check a specific key in the registry like below…

        Dim cpuID As String = _
            My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor\0", _
                "Identifier", "n/a")
        '
        'Get all chars from the beginning of the string until the first space is detected.
        cpuID = cpuID.Substring(0, cpuID.IndexOf(" "))

        MsgBox(cpuID)

If the key has x86 then its 32bit. If the key has AMD 64 or Intel64 then Windows is 64 bit. You can also check the registry key’s text to see if it contains AMD64 or Intel64. Of course if it contains x86 then the os is 32-bit and its 64-bit if it contains AMD64 or Intel64.

        'You can also check the registry string in this way.
        If LCase(cpuID).Contains("amd64") OrElse LCase(cpuID).Contains("intel64") Then

            MsgBox("It Is 64 Bit!")

        End If

I also want to show a simple way of checking if your application is running in 32 bit or 64 bit mode. You can simply check the size of IntPtr. If the pointer size is 4 bytes then its 32 bit. If its 8 bytes then its 64 Bit. This code simply checks if the size is higher than 4 or not. If its higher than 4 then its 64 bit. Otherwise its 32 bit. Remember, this method is the mode at the application level and not the platform level.

        'Basically if the Integer Pointer size is 4 then its 32 Bit and 8 is 64 Bit
        If IntPtr.Size > 4 Then

            MsgBox("64 Bit!")

        Else

            MsgBox("32 Bit!")

        End If

This post was mainly to give you an overview of a couple methods I used in the example program I made. The best thing would be for you to download the example and check out all of the methods I’ve come up with (or found out about).

I might add more to this little article in the future. That’s all for now. Have fun!

Jason

Open a Folder/Directory and Select/Highlight a Specific File

Have you ever seen a program that can open a files destination/containing folder and also highlight/select the filename as well in the opened folder window? This will show you a simple way to do the same thing. Basically your using shell to access explorer.exe while passing certain command line arguments. All versions of Visual Basic and Visual Basic.NET can easily interface with with the explorer.exe process. VB.NET, VB 2008, Visual Basic 2010, and higher will use the same code. VB 6.0 will need an additional piece of code to open the process. The target .exe and argument text passed on are used for all VB’s however.

VB 6.0 will need to add the API shell code below to the Declarations section…

Private Declare Function ShellExecute Lib “shell32.dll” Alias “ShellExecuteA” ( ByVal hwnd As Long , ByVal lpOperation As String , ByVal lpFile As String , ByVal lpParameters As String , ByVal lpDirectory As String , ByVal nShowCmd As Long ) As Long

 

Then call the ShellExecute function and pass the proper parameter arguments.  Here is the code to open the folder and select a filename using VB 6.0…

ShellExecute  Me.hwnd, vbNullString, “explorer” , “/select,” & “c:\myFileToOpen.zip” , vbNullString, 1

 

Visual Basic .NET has built-in support for running shell based code by using the Process class. Using this class is very simple. Just add the proper arguments and parameters like below…

Process.Start( “explorer” , “/select,” & “c:\myFileToOpen.txt”)

Thats all there is to it! As you can see its a very simple code to perform this functionality. Hope this little snippet and article proves helpful to you!

Jason

Revised: 2014

Target CPU and why you may get: “An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)”

An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

I remember getting quite annoyed a long time ago when I would get that error message above. Although it happened a few years ago I decided to write a brief post about it now anyways. You need to remember that this error message could possibly occur in different scenario’s and not just the way I got it.

I was trying to setup an example using VB 2005 that used a static.DLL file I made with C++. Whenever I would call a function from the DLL I would get the error message below…

‘BadImageFormatException was unhandled’

“An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)”

Picture of the Bad Format Error Message


It took some time and the advice of someone to find out why the problem kept popping up.

I use as my main computer an Intel Core2 based Processor/CPU which has 64 Bit support (x64 or AMD64, Intel64 is a clone of AMD64, which is the code name). Anyways, I use Windows Vista 64 Bit. That’s obviously not a problem in itself. I made the .DLL I mentioned above long before I upgraded to Vista 64. (BTW this error message will popup as well when running Windows7 64 Bit, and newer as well) The C++ .NET .DLL I made was based on Visual Studio.NET 2003 which will only compile 32 bit assemblies and was written when I still used Windows XP Professional 32 Bit (x86). Of course that’s not a problem in itself either. (Microsoft says .NET older than 2005 should Not be used for programming on any variant of Vista). The problem was when the two came together. I use Visual Studio 2005 Standard Edition which can target both 32 Bit and 64 Bit CPU’s and by default the profile is – Target CPU: AnyCPU. Since my CPU was running on a 64 bit Operating System, Visual Studio.NET would try to target using 64 Bit profiling instead of 32-Bit which the .DLL was written in. And that turned out to be the reason I kept getting that incorrect format error message. The program was targeting 64 Bit mode but the .DLL library I was using was 32 bit.


Picture of the Target CPU Compile Screen

To fix the problem all I had to do was change the: Target CPU: to ‘x86’ which is 32 Bit mode under the:

‘Project’ Menu: then under your project’s ‘Properties’: then under the ‘Compile’ Tab, and then ‘Advanced Compiler Settings’ which will have a small ComboBox near the bottom to select the ‘Target CPU’ to use, which I set to x86 in my case. But ‘x64′ is also available. In version 2010 of Visual Basic you can target Intel’s ‘Itanium’ processor as well..

I then re-ran the program and the calls to the .dll worked exactly like its supposed too. So if you ever get that Bad Format error message and your programming in 64 Bit mode you may try changing the Target CPU to x86 instead of the default AnyCPU (Or vice-versa).

Note: Visual Basic 2005/2008/2010 Express Edition IDE can also target a cpu architecture or platform but you change the settings in a different way using the configuration manager.

Jason

Revisited: 2015

Download Files with Advanced Features in VB 2008, Visual Basic 2010, and Higher

The .NET Framework has always made it easy to download files. But Dot.NET 2.0 added a new Async version of the DownloadFile feature. That basically means that if you use the DownloadFileAsync() sub it will download on a separate thread instead of consuming your application thread which makes your application appear frozen. If you used the regular DownloadFile and didn’t want your app’s thread tied up while downloading, you would have to spawn a new thread for the download. So Microsoft made it a little easier to download a file by adding the DownloadFileAsync method. This article and example works with Visual Basic 2008, VB 2010, and Visual Basic 2013 as well.

Updated 2015: I recently added some extra code to this article near the end. The code will add handlers for the DownloadProgress and DownloadCompleted events.


This is a simple article that will briefly highlight Downloading Files but the bulk of the code is in a VB.NET example program I made. There is way to much code to add here. The example application will not only show how to download files using the DownloadFileAsync method, but also how to add advanced features and capabilities that are not explicitly available in the DotNet 2.0/3.5/4.0 framework.

Below are some of the major features of the example project…

  • Download Progress updates like how many Bytes has been downloaded and the total size of the download.
  • Calculate the approximate download speed.
  • Calculate how long it will take the download to complete.
  • Keep track of how long the download has been active.
  • Keeping track of the Peak download speed.
  • Keeping track of the Average download speed.
  • Getting the current Downloading Status
  • Keeping track of the downloading progress and when its finished and more!

This is the base DownloadFileAsync sub I used below…

Public Sub DownloadFileAsync(ByVal address As System.Uri, ByVal fileName As String)

That method is part of the: System.Net.Webclient class. Webclient contains some very easy to use methods for uploading, downloading, and etc.

While the ‘MY’ feature has a default instance of DownloadFile under: My.Computer.Network, it unfortunately doesn’t have the DownloadFileAsync instance. So first of all to get started downloading you need to create a new instance of the Webclient class.

        '
        'Create a new instance of the Webclient class.
        Dim downloading As New Net.WebClient

You now have the DownloadFileAsync feature at your fingertips. Just simply call the subroutine while specifying the required parameters. Check the example code below…

        '
        'Will be used to setup the download url.
        Dim uriSource As Uri
        '
        'Setup a new Uniform Resource Identifier with the address to the file you want to download.
        'By the way the link in the code snippet below doesn’t work.
        uriSource = New Uri("http://www.vbcodesource.com/myFileToDownload.exe")

You can now get started performing the actual downloading.

        '
        'By using the Async version of DownloadFile your applications thread won’t be focused
        'on the download and thus you can still interact with your application. The only way
        'to get that feature with the regular DownloadFile method is by running it in a
        'seperate thread which is no longer required since an async version is availble.
        downloading.DownloadFileAsync(uriSource, "c:\MyDownloadedFile.exe")

That’s really all there is to it to get basic downloading support for your applications. If you want download progress, size, speed, time left till the download is finished and more, click this link to download the example project I mentioned earlier made with Visual Basic 2005. The program can be used in Visual Basic 2008 and Visual Basic 2010 as well.


I wanted to mention the Webclient class has two events you can use. They are Download Progress and Download Completed.

Public Event DownloadProgressChanged(ByVal sender As Object, ByVal e As System.Net.DownloadProgressChangedEventArgs)

Public Event DownloadFileCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)

All you have to do is Add Handler’s to each of those events to get reports each time data is received and when the file has finished downloading.

Edit: I added some simple code below on how to setup the two handlers.

Here are the Subroutines fired when the events are activated.

    'This will be fired whenever the DownloadProgress based event is hit.
    Sub getDownloadProgress(ByVal sender As Object, ByVal e As System.Net.DownloadProgressChangedEventArgs)

        'Update the progress bar and percentage label.
        pbDownloadProgress.Value = e.ProgressPercentage

    End Sub

And

    'Will fire when the download has ended.
    Sub downloadHasEnded(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)

        'Display the download has finished or was canceled.

        If e.Cancelled Then
            '
            'Show that the download had been canceled.
            Msgbox ("Status: Canceled")

        Else

            'Show that the download finished gracefully.
            Msgbox ("Status: Finished!")

        End If

    End Sub

This will set the above Subs to handle the events.

    'This sub will setup the event handlers for the program.
    Sub setupEventHandlers()

        'The getDownloadProgress Sub will fire whenever the DownloadAsync method updates the file
        'download status.
        AddHandler downloading.DownloadProgressChanged, AddressOf getDownloadProgress

        'The downloadHasEnded Sub is fired each time a download finishes.
        AddHandler downloading.DownloadFileCompleted, AddressOf downloadHasEnded

    End Sub

A picture of what the example application looks like


The application example highlights much more than the code in this article. So if you want, or ever needed to download file from the internet then this Link will get you a example project with full source code. Have Fun!

Jason

Revised: 2015

Detect when Removable USB Volume Drive Devices are Attached or Removed – VB.NET

Below is some code I saw on a vb message board along time ago but I can’t remember where. It may have been vbforums.com. I made some code changes and then tested the code to have it throw a messagebox with the drive letter of the new usb device being attached or removed. It uses application subclassing to intercept the messages and checks if any are activated by a removable volume being Removed, Inserted, Attached, etc.. If it is then it will parse the volume drive letter of the device and throw a messagebox letting you know. USB devices like flash drives (Thumb Drives or Pen Drive’s as they are also called), external hard drives, etc. with a removable disk volume should be detected just fine. My testing recognized different usb volumes with no problems. You can use this code with VB.NET, Visual Basic 2008, VB 2010, 2013, etc. to check for both the arrival of usb volume devices and the removal. You can also make some changes to make it work for VB 6.0 as well. Visual Basic 6.0 will need an addiional API call or two for the subclassing portion.


These go in your declaration section of your program.

    '
    'The messages to look for.
    Private Const WM_DEVICECHANGE As Integer = &H219
    Private Const DBT_DEVICEARRIVAL As Integer = &H8000
    Private Const DBT_DEVICEREMOVECOMPLETE As Integer = &H8004
    Private Const DBT_DEVTYP_VOLUME As Integer = &H2  '
    '
    'Get the information about the detected volume.
    Private Structure DEV_BROADCAST_VOLUME

        Dim Dbcv_Size As Integer

        Dim Dbcv_Devicetype As Integer

        Dim Dbcv_Reserved As Integer

        Dim Dbcv_Unitmask As Integer

        Dim Dbcv_Flags As Short

    End Structure

 

Now for the subclassing based code. This is where it starts to get alittle difficult…

Continue reading

How to Check if the Operating System is 32 Bit or 64 Bit using VB.NET, VB 2010, and Newer

I’ve seen many questions posted about how to check if the operating system the user is running is 64 Bit supported or just 32-Bit capable. 32 Bit is also referred to as x86 and 64-Bit is referred to as x64.

Update: October 19th 2010 – I decided to go ahead and add the simple code for checking OS Addressing to a new method if you use Visual Basic .NET 2010 and VB 2013.

Update 02/28/2011: I want to mention that I have another article for checking if the OS is 32bit/64bit, but also if your application is 32-bit/64-bit at this link here.


For Visual Basic.NET 2010 Only…

 Environment.Is64BitOperatingSystem

That property was added with the .NET Framework 4.0. Simply get the value from that property like below…

MsgBox(Environment.Is64BitOperatingSystem)

The property is a Boolean so it will return True if the Operating System is 64-Bit, otherwise it will return false.
If your not using VB 2010, 2013, and higher then continue reading the article…


Visual Basic.NET Older than version 2010

I’ve seen various options people have come up with like checking WOW64 emulation , ect… I’m not going to get into all of them. From what I understand those methods may not be 100%. So far in MY EXPERIENCE my version has been 100% when used with Vista and Windows 7. That is NOT to say that its perfect or has no flaws. Its just I have not had any problems, yet…

Anyways, its a very simple solution. Use the Windows built-in WMI (Windows Management Instrumentation) objects and features. Using WMI is quite easy with .NET. I unfortunately won’t be providing VB 5 or Visual Basic 6.0 source code. But the basics are still the same. I think VB classic can get support by referencing the WMI Scripting Library or using some API’s.

The apparent downside is that Microsoft says this wmi method is not supported on Windows XP. You can use environment variables and getnativesysteminfo api to query the os addressing. This wmi method so far appears to work just fine using Vista and Windows 7. 64 Bit operating systems became VERY popular with Vista, and especially Windows 7 due to ram being so cheap and if you wanted to address more than the 32 Bit limit of 4GB you needed to have an OS that can do 64 Bit addressing and a cpu capable of using AMD’s 64 Bit extensions. Intel CPU’s actually use AMD64 technology for their 64 Bit processors (Less Itanium)).

First of all in DotNET you want to add a Reference to two classes under: System.Managment. This will provide features to access wmi classes and features with minimal coding on your part. Of interest is the Management Class and the Management Object.

Below is the complete WMI based code that is used to get the Windows info…

    '
    'This function uses the WMI method to see if the operating system return 32-bit or 64-bit.
    Public Function getWMIInfo(ByVal wmiObjectInfo As String, ByVal wmiRelativePath As String) As String

        Try
            '
            'Give it something to report in case something wrong happens.
            getWMIInfo = "Nothing!" '

            Dim wmiClass As New System.Management.ManagementClass

            Dim wmiObject As New System.Management.ManagementObject

            wmiClass.Path.RelativePath = wmiRelativePath
            '
            'This will go through each item in the requested info. I only care about
            'the 1st for the most part but remeber that each instance could have different values.
            For Each wmiObject In wmiClass.GetInstances

                getWMIInfo = (wmiObject(wmiObjectInfo))
                '
                'I only want the first instance.

                Return getWMIInfo

            Next

        Catch exc As Exception

            Return exc.Message

        End Try

    End Function

Now all thats left to do is provide the object and path your interested in. The code below will throw a Messagebox with the message “32-bit” if your OS is x86 or “64-bit” if your OS is x64.

        '
        'Supply the WMI Object and Path to get whether the os is 32-bit or 64-bit.
        MsgBox(getWMIInfo("OSArchitecture", "Win32_OperatingSystem"))


That’s all there is to it! Like I said, so far its worked fine for me. Thats not to say there won’t be problems though. I will upload a new example I made at my vbcodesource.com website that shows how to get the Operating System and Applications addressing whethers its 32 Bit or 64 Bit that works with Windows XP, Vista, and Windows 7. Definitely, Let me know of any problems you run into using the source code in this article! Anyways have fun!

Jason

Revised: 2015

Updated: USB using Visual Basic.NET and VB 6.0

The purpose of this post is simply to give some info to help with usb programming like detecting when a usb device has been added/removed, which the .NET based class helps with, ect…


Visual Basic 6.0

The first library is for Visual Basic 6.0 and is provided by Intel (Intel is the main inventer of USB as well) and includes various bas/modules for use in your applications. BTW, these  VB 6.0 USB modules do more than the below .NET library.

Click here for the Main Intel page with the downloads and tutorial…

Edit: The Intel link above is no longer valid. I have not been able to find where it was moved to or if its completely taken away. I still have the VB Bas files that are needed to do the USB programming.

Click here to download the modules.


Visual Basic.NET Compatible Class Library

Strolling through some of the latest updates at thecodeproject.com I noticed someone made a USB library using C# for detecing the attachment and detachment events of usb devices. He provides the source code, compiled class, and a demo app with the usb library in action. If you simply want to reference the class download the source code version. Then under the Bin/Release directory you will see the ‘USBClassLibrary.Dll’ which is what you want to reference.

Click here for the main USB Library page…


Hopefully this post was of some help. Have Fun!

Jason

“How Do I” Videos for Visual Studio 2010 and Release Candidate Available

The RC1 download is Obsolete. Others seems to work still.


As expected Microsoft is already starting to release some new videos related to VB 2010 and will continue to add new video’s/codes to highlight new features in the new IDE/Framework. Also, Release Candidate1 of Visual Studio 2010 has been released. Check out this link if you want to check out RC1.

Below are some highlights from the Microsoft HowDoI post…


If you haven’t seen these yet, various members of the languages team have released some How Do I videos on Visual Studio 2010 including new language features in Visual Basic 10 and C# 4.

  1. How Do I: Use Autoimplemented Properties in Visual Basic?
  2. How Do I: Use Implicit Line Continuation in Visual Basic 10?
  3. How Do I: Use Highlight References in the Visual Studio 2010 IDE?
  4. How Do I: Use Code Snippets in the Visual Studio 2010 IDE?
  5. How Do I: Use Generate from Usage in Visual Studio 2010?
  6. How Do I: Enhance Performance in the Visual Studio 2010 IDE when Editing VB Code?
  7. How Do I: Step with The Debugger in Visual Studio 2010?
  8. How Do I: Use Named and Optional Parameters in C# 4.0?
  9. How Do I: Use COM Interop and Office in C# 4.0?

Also make sure to check out the VS 2010 code samples and walkthroughs.

Enjoy!


If you want to check them out, goto this link to the main post page. Take care! 🙂

           Jason

Revisited: 2015

Expired- Some Free Training and Tutorials from AppDev

Promotion has ended

 

I’ve posted on this site before some free tutorials/training courses from AppDev and now they are offering three more for free. I’m fairly sure that these have not been posted here before. The three free tutorials they are offering right now is Not directly related to VB.NET. They are more in-line with ASP.NET and Visual Studio, Sharepoint, ect… Either way it may be worth it for you to check them out. All you really have to do is login/signup for your account and download.

———————-

 

Free ASP.NET and AJax Training –

Basic Overview…

Start learning Microsoft® ASP.NET or AJAX with award-winning training from AppDev! Your free training is taken directly from our actual courses, and features step-by-step presentations and code walkthroughs by our Microsoft MVP and expert instructors. Most courses also include extras like:
aHands-on lab exercisesaSample CodeaPrintable coursewareaPre/post exams

 

———————-

 

Free Visual Studio 2008 Training –

Basic Overview…

Start learning Microsoft® Visual Studio® 2008 with award-winning training from AppDev! Your free training is taken directly from our actual courses, and features step-by-step presentations and code walkthroughs by our Microsoft MVP and expert instructors. Most courses also include extras like:
aHands-on lab exercisesaSample CodeaPrintable coursewareaPre/post exams

 

———————-

 

Free Sharepoint Training –

Basic Overview…

Start learning Microsoft® SharePoint® 2007 with award-winning training from AppDev! Your free training is taken directly from our actual courses, and features step-by-step presentations and code walkthroughs by our Microsoft MVP and expert instructors. Most courses also include extras like:
aHands-on lab exercisesaSample CodeaPrintable coursewareaPre/post exams

 

———————-

 

Thats about it for now. I have NOT seen any of these tutorials so I don’t know how good/bad the content is. If you watch them feel free to leave a comment with your opinion about the courses. Take Care…

Jason