Tag Archives: my.

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

Use Custom MY.MySettings to Remember an Applications Size and Position in VB .NET

Note:  This article is aimed at the Visual Basic .NET 2005/VB 2008 and Newer versions since the earlier versions of dot net do Not have the My feature. But the principals still apply if your using an older version of vb.net.

This small tutorial is to show you how you can create your own properties using the ‘My.MySettings’ Class. This article will focus on adding Two new properties/settings called: ApplicationSize and ApplicationPosition. I will use them to store the applications position and Size when it exits or closes. Then the next time the application/program loads, it will use these settings and remember the exact Position and Size from the last time it was opened and closed.


Once you have your project loaded, goto the ‘Project’ menu and select the ‘Properties’ option from the list, which is usually the last item listed. Then select the “Settings” Tab item. You will then see the settings grid which is used to configure the application settings.

Name: This is where you put the name of your property/setting. For this tutorial, put in ApplicationPosition as a name, and ApplicationSize as another name. ApplicationSetting and ApplicationSize will actually be listed under: My.MySettings.Default.

Type: Here you can select the type you want your setting/property to be. Example: Point, Size, Date, Integer, and so on. For the article, set the type for ApplicationPosition to be: ‘Point’. For the ApplicationSize set to be the: ‘Size’ type.

Scope: This is where you can specify if the property/setting can only be modified by your Application, or if the person using your application can change the setting. If ‘Application’ is set, then the user cannot modify the setting at runtime. If ‘User’ is selected, then the setting Can be modified at runtime by the user. If you want to have certain preferences that the user can modify, then ‘User’ is the scope you want to use. For the article I went ahead and set it to ‘User’.

Value: You can specify a default value for the property/setting that will be used if the property is being used for the first time or no other value have been specified at runtime. This value will also be used if you ‘Reset’ the properties. Example: My.MySettings.Default.Reset() will reset the settings to your original values.


If you are following the article as a exercise, then your Project Properties should look similar to the picture below (IF you can read it that is…


Under the: My.Settings.Default interface, you should have: My.MySettings.Default.ApplicationPosition and My.MySettings.Default.ApplicationSize available as properties that can now be used. To get your application to use these properties and enable it to remember the size and position to load, you will want to put a few lines of code in the Form_Load event, and the Form_FormClosing event.


Form_Load Event put:

        Me.Location = My.MySettings.Default.ApplicationPosition

        Me.Size = My.MySettings.Default.ApplicationSize

Form_FormClosing Event put:

        My.MySettings.Default.ApplicationPosition = Me.Location

        My.MySettings.Default.ApplicationSize = Me.Size


That’s all there is to it. Now your application will have the ability to memorize the position and size when it was previously ran and can load in the same position and at the same size. You do NOT need to specifically use the registry or create a ini file to enable these user-friendly capabilities.

    There ARE more features and properties available for creating custom properties/settings, but those will have to be covered in a future article. Hope you got something worthwhile from this small tutorial 🙂

    Click Here for a example application with this article.


How to use Visual Basic.NET Source Code and Features in VB 6.0

There is no doubt the .NET Framework contains some rich and very useful objects to make many task very easy to do. Unfortunately Visual Basic 6.0 does not have direct access to these great features. BUT, all is not lost. You can create a COM Wrapper in Visual Basic.NET (I used VB 2005) to make features of the DotNETFramework available to the Legacy/Classic versions of Visual Basic. You can also use VB 2008 and Visual Basic 2010 (Express Edition should be just fine) if thats what you have.

Note: The example projects for this article has been done for a very long time and I forgot about putting a download link on this article. So here are the download links!

VB 6.0 Project with Compiled .NET Wrapper

VB 2005 Project with Compiled .NET Wrapper

Getting Started…

The first thing you would want to do is open up your Visual Basic.NET (Any version is fine as far as I know?.? I am using VB 05 in this article.) IDE and start a new Class Library project. Also, the actual Ping codes are NOT available in Visual Basic.NET 02/03. The principals in the article are the same but the actual Ping code will not work in the earlier dotnet languages. Now, Go ahead and just delete the original Class1.vb file since it is of no use for Fusion. Next goto the Project Menu and click on – Add New Item (Or you can click on ‘Add Class’ for VB 05/08) and select the ComClass Module. I named mine ‘pingWrapperForVB’. I went ahead and added a Reference to System.Windows.Forms since I wanted to use the more advanced MessageBox.Show feature instead of the legacy Msgbox. I also Imported the Namespaces below this image.

Adding the ComClass view

Add these Import Statements right above your Class.

Imports System.Net.NetworkInformation

Imports System.Windows.Forms

Important Note: When adding a COM Class it should automatically check the ‘Register for COM Interop‘ box. If it didn’t then you should go to the ‘Project’ menu and click on the ‘Project Properties‘ item. Click on the Compile option and scroll to the bottom of the page. You should see the ‘Register for Interop‘ checkbox. Make sure that checkbox is checked.

Important Note #2: Just remember if your program is going to be used on a computer other than the Developer computer, then you will need to register the .NET Managed wrapper as a COM object in the Windows registry. Click this link for more information.

Then I created a Public Function named: ping_AddressReply with Two (2x) parameters named (URL as String and TimeoutInMS as Integer) and it returns a Boolean type. I made the TimeoutInMS Parameter a Optional value with a default of 10 Seconds. This Function will be used to send a ping request and get the return value of the request, either ‘True’ that the Ping was successful or ‘False’ if it was not successful.

I then added just a basic Try/Catch/End Try feature that will throw a Ping Exception in a Messagebox if something didn’t go quite right. You can do your own error handling though. Within the Try/Catch structure I added the small piece of code below…

        'Simply sends a Ping request using the URL Parameter and the Timeout Parameter. I made the
        'timeoutInMS Parameter optional with a default value of 10 seconds.
        Return My.Computer.Network.Ping(url, timeoutInMS)

Setup the next Function the same as the first. Except making the Function type a Integer. Remember that VB 6.0 will see the .NET Integer as a Long. I named the Function ‘New ping_AddressTimeItTakes‘ as Integer. Then simple add the codes below inside the Try/Catch structure…

        Dim p As New Ping

        Dim reply As PingReplyreply = p.Send(url, timeoutInMS)

        Return CInt(reply.RoundtripTime)

You are now done with the wrapper. Look over your codes one last time to make sure they are correct and then compile the class library. You are now ready to use the wrapper in Visual Basic 5.0/6.0. Now load your VB 5.0/6.0 IDE and create a new .EXE Project type. I named mine: ‘PingAddressWrapperEx‘. I likewise I added 2x Labels named ‘lblReply’ and ‘lblTime’, a Textbox for the url I named: ‘txtAddress’, and 2x command buttons.  Name the buttons whatever you want to. Now goto the ‘Project’ menu and click on the ‘References’ menu item. Click on the Browse button and locate your .NET Project and goto the ‘Bin’ Directory (or where the compiled class is). Add a reference to the ‘TLB’ file and NOT the .DLL file. VB 6 cannot use the .DLL class directly and thus you need to reference the TLB file to get access to the .DLL in VB 5.0 and VB 6.

A reference view in VB 6.0

Once you create a reference to the TLB file, then add the line of code below in the declaration section…

        'I’m using ping to refer to the Wrapper.
        Dim ping As pingWrapperForVB6.pingWrapperForVB6

Once you take care of that, put the codes below in your command buttons…

    Private Sub cmdPing_Click()

        'Check if a instance of the class already exists, and if it isn’t then create a new instance of the ping wrapper.
        If ping Is Nothing Then

            'Create a new instance of the wrapper.
            ping = New pingWrapperForVB6.pingWrapperForVB6

        End If

        'Send the ping request and get the True or False messages.
        lblReply.Caption = "Replied: " & ping.ping_AddressReply(txtAddress.Text)

    End Sub

Likewise, put the codes below in the other command button…

    Private Sub cmdSendTime_Click()

        'Check if a instance of the class already exists, and if it isn't  then create a new instance of
        'the ping wrapper.
        If Ping Is Nothing Then

            'Create a new instance of the wrapper.
            Ping = New pingWrapperForVB6.pingWrapperForVB6

        End If

        'Send the ping request and display the time it takes to get a reply.
        lblTime.Caption = "Round Trip Time: " & Ping.ping_AddressTimeItTakes(txtAddress.Text, 10000) & "ms"

    End Sub

You can now run your project and put in the URL you want to ping. I put in: vbcodesource.com but you can put the url you want. But Do Not include the http:// portion of the url, it will cause the ping to fail. Now just click on the command buttons that has the code and you should see the status of the pings in the label controls…

Image of the final product :)

Hopefully you had no errors popping up. My example returned True that the url was available and a round trip time of: 42ms.  Thats all there is to it! You now have basic Ping capabilites in VB 6.0. Remember though, the target computer MUST have the version of the DotNET Framework you made the wrapper with. IF not then the Ping Wrapper will fail and you won’t have no ping capabilities. I will eventually add the actual projects for the .NET Wrapper and the VB 6 example when I get the time on my other site at: http://www.vbcodesource.com Anyways, have fun 🙂


How to get the Computer Screens Resolution using VB and VB.NET

At some point you may need to get a computers monitor/video resolution for sizing your applications and/or your applications controls/fonts or whatever. It is actually easy to do so in ALL versions of Visual Basic. Only a very small amount of additional code is required to get the Resolution in 6.0 compared to doing it in .NET. Below is doing it in VB 6.0.

Visual Basic 6.0

To get the resolution in VB Classic is quite easy. You can use the following code below…

Screen.Width – For the Horizonal Resolution.

Screen.Height – to get the Vertical resolution.

But if you use those codes by themselves, it will not return the resolution in Pixels which is probably the format you are wanting. There is an extra piece of code for getting the resolution in Pixels…

Screen.Width / Screen.TwipsPerPixelX

Screen.Height / Screen.TwipsPerPixelY

Below is the code put together with a Messagebox displaying the resolution for the screen…

'Simply throws a messagebox with the current resolution of the screen...
MsgBox("The Screen Resolution is: " & Screen.Width / Screen.TwipsPerPixelX & "x" & Screen.Height / Screen.TwipsPerPixelY)

What about the VB.NET versions? Even easier actually.

Visual Basic.NET & VB 2008/2010, and VB 2013

What we want is the Screen class located at:


This handy little Class has data related to the computers display screen. Below is a simply example…

'Simply display a messagebox with the resolution of the computers screen.

If a computer has more than one(1) screen/monitor, then you could also use the ‘Screen’ class to get the resolution for that screen.

Example: Say your application was running on a computer with Two(2x) monitors/displays and you wanted to know the resolution of the monitor your Form is shown on or the monitor that is showing the biggest portion of your Form? The Screen Class can help you with that…

'If you had multiple displays, and you wanted to know the resolution of the display
' that contains your form, this code would do that for you.


In Visual Basic 2005 and/or Visual Basic 2008, VB 2010, and newer you can even use the MY interface to access the Screen class.


'Use the MY shortcut in VB 05/08 to get the sacreen size...

Well, thats all there is to it if you wanted to get the Computers Display/Screen Resolution in your Applications. Its easy to do from Visual Basic 5.0/6.0 through to Visual Basic 2005/2008. Have fun! 🙂


Use the Registry to get CPU/Processor Hardware information using VB.NET and Higher

This is a simple article/tip of using the Windows System Registry to access the ‘CentralProcessor’ sub-key and extract information about the computers processor. You can get the cpu’s clockspeed, namestring, model, stepping, etc. Shows two ways to access the registry.

Example use is below.

Visual Basic.NET, Visual Basic 2008, and VB 2010

        'The registry path to get the info we are wanting.
        Dim str As String = "HARDWARE\DESCRIPTION\System\CentralProcessor"

        'Returns how many SubKeys are under “CentralProcessor”.
        'The subKey count under this key =’s the‘total cpu’s your system has installed.
        'My system happens to return 2x subkeys since I have a Dual Core system.
        Dim cpuCount As Integer = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(str, False).SubKeyCount
        'Get and add the values for the first cpu.
        Dim cpuMhz As String = Microsoft.Win32.Registry.LocalMachine.OpenSubKey( _

        Dim cpuName As String = Microsoft.Win32.Registry.LocalMachine.OpenSubKey( _

        Dim cpuVendorID As String = Microsoft.Win32.Registry.LocalMachine.OpenSubKey( _

        Dim cpuIdentifier As String = Microsoft.Win32.Registry.LocalMachine.OpenSubKey( _

Thats all there is to it. You just need to handle the variables that will contain the cpu data extracted. Below is similar example code for VB 05, and higher only since it uses the MY interface to access the registry…

Visual Basic 2005/2008 and VB 2010 Only…

        'The registry path to get the info we are wanting.
        Dim str As String = "HARDWARE\DESCRIPTION\System\CentralProcessor"

        'Returns how many SubKeys are under “CentralProcessor”.
        'The subKey count under this key =’s the‘total cpu’s your system has installed.
        'Of course, 90% or so will only have 1x subkey denoting a‘single cpu system.
        'My system happens to return 2x subkeys since I have a Dual Core system.
        Dim cpuCount As Integer = My.Computer.Registry.LocalMachine.OpenSubKey(str, False).SubKeyCount

        'Get and add the values for the first cpu.

        Dim cpuMhz As String = My.Computer.Registry.LocalMachine.OpenSubKey( _

        Dim cpuName As String = My.Computer.Registry.LocalMachine.OpenSubKey( _

        Dim cpuVendorID As String = My.Computer.Registry.LocalMachine.OpenSubKey( _

        Dim cpuIdentifier As String = My.Computer.Registry.LocalMachine.OpenSubKey( _

For VB 6.0 it’s not quite this simple to access the registry. Win32 API calls are required to do so. There are examples around the net that shows how to use the Win32 Registry code in VB 6.0. Have fun!


How to Easily Play Wave Files with Visual Basic.NET and Newer

It’s actually quite easy to play wave files (.wav waveform based sound files) using just alittle code in some cases. The .NET Framework 2.0, 3.5, 4.0, and higher has a managed wrapper around the PlaySound API.

The easiest way to play wave files with Visual Basic 2005, VB 2008, VB 2010, and newer is as shown below…

    'Play a wave sound file from a specified location.

    'Stop the file from playing.

    'Play a Windows system sound.

The code above simply used the MY Interface for quick access to the Audio class to play a file, stop the playback, and then playback a system sound.

What about playing wave sound files with Visual Basic.NET 2002 and Visual Basic.NET 2003?

Continue reading

Copy and Paste Text with the Windows Clipboard in VB 2005 and Higher

This uses the MY interface to Copy Data To the Windows Clipboard and to Paste Data from the Windows Clipboard. Visual Basic 2005, Visual Basic.NET 2008, and Visual Basic 2010 is supported.

Copy Text

        Set(Copy) text to the Windows Clipboard.
        My.Computer.Clipboard.SetText("This is my text", TextDataFormat.Text)

Paste Text

        'Get(Paste) text from the Windows Clipboard.

Copy, Create, Delete, and Rename a Directory/Folder using the MY Interface

This source code works for VB 2005, VB 2008, Visual Basic 2010, and higher.

'Copy, Create, Delete, and Renaming a Directory.
Dim dir AsString = "c:\Directory"'

'Create a directory with the path and name specified in the dir string variable.

'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)

Download a File from the Internet to the Hard Drive using VB 2005 and Higher

This will simply download a file from the internet to your harddrive path using Visual Basic .NET 2005 and Higher up to VB 2008, and VB 2010. This code snippet uses the Network class under the MY interface that was introduced in Visual Basic 2005.

        'Download a specified file from the internet and put it in the specified directory.
        My.Computer.Network.DownloadFile("http://www.webAdress.com/page.html", "c:\thePage.html")

Get the Operating System: Name, Platform, Version, and Service Pack using VB.NET 2008 and higher

This will return the Windows Operating System Name, Platform, and Version using the MY interface under VB 2008, Visual Basic 2010, and 2013. Then from the System.Environment class it will get the operating systems installed Service Pack, and then the entire OS info in one string value.

'This will throw 5x messageboxes with the FullName of the Installed Windows, along with
'the OS Platform, OS Version, the service pack installed, and then a message show all
'of the information about windows. that your program is running on. This works with VB 2005,
'Visual Basic.NET 2008, and Visual Basic 2010

Revised: 2015

Get the Total Installed Physical (Ram) and Virtual Memory in .NET 2008/2010 and Higher

This will work for .NET 2.0, and higher. It uses the MY interface.

'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”)

How to get the Computers Monitor Display Resolution using VB 2005 and Higher

This shows how to use the MY interface to check what the resolution is for the Primary Display. This will return the size in Pixels. Since i’m using the MY interface, the code will only work with VB.NET 2005, VB 2008, and Visual Basic 2010.


'Get the displays current Resolution.
MsgBox("Resolution is: " & My.Computer.Screen.Bounds.Width.ToString & "x" _
    & My.Computer.Screen.Bounds.Height.ToString & " Pixels")


Play and Stop a Wave File or System Sound using VB 2005 and Higher

This shows how to use Visual Basic.NET 2005, VB 2008, Visual Basic 2010, and 2013 to play a wave (.wav) file and/or play a Windows SystemSound. This uses the MY interface which uses the SoundPlayer class new to .NET 2.0.

        '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)




Use the ‘MY’ interface in VB 2005 and Higher

Visual Basic 2005 and Higher contains a unique feature which is the ‘MY’ interface. In fact, Visual Basic is the ONLY .net language at this time that even has this interface. Under the MY interface is a list of categorys ranging from Application to Webservices for you to choose from. You can think of MY as sort of a Shortcut menu. For instance, if you wanted to use the DoEvents() Sub you can do it the MY way or the typical way.

        'Typical way,
        'MY way,

So the MY way saved a step or 2 if none of the namespaces has been imported.

Another example is playing a sound using the Audio class.

        'Typical way,
        Dim audio As New Microsoft.VisualBasic.Devices.Audio
        'MY Way,

Again, there are a few steps saved using the MY interface. These are just a couple examples of a great many features the ‘MY’ interface gives us VB programmers.