Category Archives: Articles

A collection of various articles for Visual Basic.

How to Playback a Audio Compact Disk (Play/Stop/Pause a CD) using VB and VB.NET

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (10 votes, average: 4.10 out of 5)
 

Thankfully playing audio based .cda cds is an easy process and does not require having to rely on 3rd party controls. You can simply use the Microsoft Windows MCI Command Interface to do this. As you may be aware of you can do almost all of your Media based playback needs by using this interface including playing movie files. I do plan on making a new article on playing movie files in the future. I have a complete tutorial with some source code on how to use and program the mciSendString API so you can get a much deeper understanding on how it works and how to use it. Click on this link if you want to read it.

To get started you first need to setup the main API call that is required. Simply add the API below to your declarations section…

_____________________________

Visual Basic 5.0/6.0….

'
'Api call to send the commands to the mci device
Private Declare Function mciSendString Lib “winmm.dll” Alias “mciSendStringA” (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal uReturnLength As Long, ByVal hwndCallback As Long) As Long

Visual Basic .NET…

'
'Api call to send the commands to the mci device
Private Declare Function mciSendString Lib “winmm.dll” Alias “mciSendStringA” (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal uReturnLength As Integer, ByVal hwndCallback As Integer) As Integer

_____________________________

Now that the main API call is setup and declared you need to start using it to program the device and send it commands. The first thing you need to do is create a new device and set the device to use the CDAudio driver. As you may have guessed this driver will do AudioCD playback. Below is how to create a new device using the CDAudio driver.

Note: In this article if your using VB 5/6 you only need to change Integer or Int32 types to Long types.

_____________________________

'
'This will hold the mci return value. The value in this variable will not be used in this article however.
Dim retVal As Integer
'
'This will be used to specify the drive letter of the CD or DVDRom drive to use.
Dim cdDrive As String
'
'This should be set to the CD or DVD drive your Music CD is in.
cdDrive = "D:\"
'
'Add quotes which will keep from having to get the short path since the mci device could fail if using the normal long file and path. Remember to set cdDrive to the CDRom or DVDRom optical drive. Specify like: D: or D:\ if D is your drive, or E: or E:\ and so on.
cdDrive = Chr(34) & cdDrive & Chr(34)
'
'Create a new CDAudio device with the alias CD. “CD” is how we will refer to the device  in this program.
retVal = mciSendString(“open “ & cdDrive & ” type cdaudio alias cd wait shareable”, vbNullString, 0, 0)
'
'Send the command to set the time format to the device default. Set this so when asking for time/track information we can get the value as a Tracks/Minutes/Seconds/Frames format.
retVal = mciSendString(“set cd time format tmsf”, vbNullString, 0, 0)

_____________________________

Now that a device has been created to use the CDAudio driver its time to start sending some commands.

_____________________________

The code below will return the total number of tracks on the audio cd in the cd drive…

'
'This variable is used to receive the value when requesting information from the mci device.
Dim buf As String
'
'Give it a 128 space buffer.
buf = Space(128)
'
'This will get the total number of tracks returned from the device.
Dim trackCount As Integer

retVal = mciSendString(“status cd number of tracks”, buf, 128, 0)
'
'Get the integer value from the buffer. It will return 0 (zero)  if no tracks are detected or if no audio cd is present.
trackCount = CInt(Val(buf))

_____________________________

If trackCount has the number 12 then there are 12 tracks starting at Track #1 through to Track #12. So when referring to a specific track you need to specify the exact number you want the information from.

Next you can now go ahead and start Playing, Stopping, and Pausing/Resuming a Audio CD’s tracks. First you want to tell the device which track you want to play. The next set of codes will do that.

_____________________________

'
'This will hold the track number to play. It is then set to track 2 below.
Dim trackToPlay As Integer
'
'Set to play Track number 2 on the compact disk.
trackToPlay = 2
'
'You need to set the time format to the cd devices default so it knows that 1, 2, 3, 4, and so on is the track number.
'Set the time format to the cd devices default Tracks, Minutes, Seconds, Frames when you are wanting to seek to a specific track.
retVal = mciSendString(“set cd time format tmsf”, vbNullString, 0, 0)
'
'This will tell the device to move to the track number specified. Simply put in the track number you want to play.
retVal = mciSendString(“seek cd to “ & trackToPlay, vbNullString, 0, 0)

_____________________________

You can now start Playing, Stopping, Pausing, and whatever it is you want to do.

_____________________________

'
'Start playing the cd at the track you already specified above.
retVal = mciSendString(“play cd”, vbNullString, 0, 0)
'
'Stop the cd from playing.
retVal = mciSendString(“stop cd”, vbNullString, 0, 0)
'
'Will pause the CD if its playing.
retVal = mciSendString(“pause cd”, vbNullString, 0, 0)
'
'Resumes the cd to playing if it was paused.
retVal = mciSendString(“resume cd”, vbNullString, 0, 0)

_____________________________

Thats ALL there is to it! IF the codes in this article was properly implemented then it should Start, Stop, Pause, and Resume an Audio Compact Disk (CD). There is MUCH more you can do with Audio CD’s as well like getting the length, position, fast forward, Opening/Closing the CD Door and so on. But some of those features might be implemented in a future article.

I suggest you really go check out my MCI Command tutorial this site, or an older revision but downloadable .doc version so you can try and learn how to actually implement your own custom functionality and possibly checking out the documentation at microsoft.msdn.com.

If you don’t care or have the time to create your own source code for audio CD based playback then you can check out my AudioCD based class libraries. My vbcodesource.com website has MANY libraries available that greatly simplifies the task of creating a CD player based application. I even recently released a brand new library named csAudioCD Library v2.5 Pro Enhanced for Visual Basic 2005 and VB 2008 that has Over 50 subs and properties. I have libraries for VB.NET 02/03 and VB 5.0/6.0 as well. I suggest you goto my main website under the controls and examples section if your interested. There are example applications available as well on how to use the audio cd libraries.

Anyways, I hope you got something useful from this article and it was easy to understand as well. Sometime in the future I may expand on this subject by showing how to get position, duration based information and such. Have Fun!

Jason

How to Open a Url or Link in Default WebBrowser – VB 6.0

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (10 votes, average: 3.80 out of 5)
 

I figured this would be very easy to do since VB has a Shell command built-in. But I would keep getting a File not Found message everytime I would try and open a web address. It would work for other tasks like shelling “shutdown -r -f -t 0” which is a process that can be be used to shutdown or restart the computer, but not opening a URL. So I decided to go ahead and use the Windows APIs to do this task. Below is the API Call and codes to open a url in the default web browser.

____________________________________

This Function will be used to process the url which will have windows open the web browser pointing to that url path.

    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

Now all thats needed is to execute that function passing the url you want opened in the third parameter. For this task the 3rd parameter is the most important. Well, I guess 2, 3, 6 should be set. Parameter #2 is how to process the task in the 3rd parameter which will be set to “open”. You could just put a blank string like “” which will still open the url. But just enter “open” to be on the safe side. Parameter #6 is the window style to open the application. Like 1 is for normal and such. As far as I know the other paramters is not required for this to work so I just set them to 0 or vbnullstring.

        '
        'In the last parameter you can specify the program window style.
        '0 = Hide, 1 = Normal, 2 = Minimize, or 3 = Maximize.
        '
        'For other styles just open the VB API Viewer application under your VB's Tools directory and open the Win32Api.txt file and check out the constants that starts with "SW" like SW_NORMAL.
        '
        'Anyways, this will have the Windows Shell open the Default WebBrowser with the url specified in the 3rd parameter.
        '
        ShellExecute 0, "open", "http://www.vbcodesource.info", vbNullString, vbNullString, 1

____________________________________

I added the next codes just to show how to open another program and pass arguments to the program. This code will launch the FireFox webbrowser and open the URL in the 4th parameter.

 

        '
        'This simply shows how to open a specific program like Firefox which may not be the default webbrowser
        'and how to get it to go to a specific url.
        ShellExecute 0, "open", "C:\Program Files\Mozilla Firefox\Firefox.exe", "http://www.msdn.com", vbNullString, 1

 

____________________________________________

Thats all there is to it!. As you can see with a simple API call you can get the job done. Anyways, have fun!

Jason

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

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (7 votes, average: 2.71 out of 5)
 

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.

                         Jason

How to add Auto Complete to Textbox or Combobox Controls in Visual Basic 2005/2008, VB.NET 2010, and newer

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (6 votes, average: 2.83 out of 5)
 

Note: This is an article which was taken from my vbcodesource.com website and is quite old. So take that into consideration… 🙂

As you will see, adding Auto-Complete support to textbox and combobox controls has NEVER been easier than it is now in Visual Basic.NET 2005. No longer do you HAVE to use the Windows API’s to get the Auto Complete functionality.

I will assume you already have a ‘Windows Application’ based project open. You can go ahead and add a textbox control or combobox control to the form. Select the textbox and goto the properties window. (I will assume you added a textbox, but the process is the same for a combobox also. I will just refer to textbox instead of combobox.)

There are 3x properties that relate to the ‘Auto Complete’ feature. You have “AutoCompleteCustomSource”, “AutoCompleteMode” and “AutoCompleteSource”. AutoCompleteCustomSource is exactly how it sounds. You can have your own text that you want the user to be able to use when they are typing in the control. But, I am not interested in going over that property right now though. There is really nothing more to it than what I already said. 🙂

OK, the “AutoCompleteMode” property is simply how the AutoComplete text responds. Click on the “AutoCompleteMode” property and then open the dropDown list associated with it. You will see 4x ‘modes’ available. “None, “Suggest”, “Append”, and “SuggestAppend”. This property MUST be selected either “Append”, “Suggest”, or “SuggestAppend” for the AutoComplete feature to work. If you select “Suggest” mode, then ‘AutoComplete’ will display a list that matches the text that has been typed thus far that you can scroll through and choose from. If you select “Append” mode, then as you are typing, it will automatically highlight the closest match to the text thus far in the textbox/combobox control, usually in alphabetical order. Plus, while you are typing, you CAN use the ‘Up/Down’ buttons on the keyboard to scroll through the list of text that is similar to the text that was typed in the textbox control. The “SuggestAppend” mode, is of course the combination of the other 2x modes. As you are typing the text, it will highlight the first occurance of matching text while also displaying a list of all the text that matches what has been typed in the control.

The “AutoCompleteSource” property is exactly how it sounds. It is the location on the computer system to get the ‘AutoComplete’ list from. Click on that property and then click on the box to dropdown the enumerator values that are available as the source. Available values, at least on my computer are: “FileSystem”, “HistoryList”, “RecentlyUsedList”, “AllUrl”, “AllSystemSources”, “FileSystemDirectories”, “CustomSource”. Just like the “AutoCompleteMode” property, you MUST select one of these values for you to get ‘AutoComplete’ functionality. Since all of the values are self-explanatory, I will not go over them.

Just to test out the ‘AutoComplete’ feature. With a textbox control, (Or Combobox), click on the “AutoCompleteMode” property and select the “Suggest” mode. Then click on the “AutoCompleteSource” property and then select “AllUrl” as the source. Run the project, start typing in the textbox ‘www’ and you should see a list of url’s you’ve visited that start with ‘www’ popup. You can then click on one of the urls and it will put that url text in the textbox.

And thats ALL there is to it! Enjoy!

Jason

 

Textbox Scroll to Bottom or Top – Part 2 using VB 6.0 and VB.NET

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (21 votes, average: 2.62 out of 5)
 


I have a previous post on how to scroll the textbox controls contents to the bottom and the top that many visitors didn’t appear to like. It has a 1.5 rating out of 10 so, it is not liked very much. I really don’t know why because the code seems to work fine. Maybe because the cursor position would be moved? This new code won’t move the actual cursor if thats the case. But anyways, I decided to post another way to scroll the textbox contents by using the Windows API. This method uses the SendMEssage function and passes a couple constants to perform the up and down scrolling process. Below are the codes for VB 6.0 and VB.NET.

_____________________________________

Visual Basic 6.0 Declarations…

    '
    'Used to Send Messages to the control and will be used with a request for the current line number in the textbox control.
    Private Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal winHandle As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
    '
    'Constants used for the SendMessage API call function.
    '
    Private Const EM_SCROLL = &HB5
    Private Const SB_BOTTOM = 7
    Private Const SB_TOP = 6

————————————————

   

   

Visual Basic .NET Declarations…

    '
    'Used to Send Messages to the control and will be used with a request for the current line number in the textbox control.
    Private Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal winHandle As _Int32, ByVal wMsg As Int32, ByVal wParam As Int32, ByVal lParam As Int32) As Int32
    '
    'Constants used for the SendMessage API call function.
    '
    Private Const EM_SCROLL = &HB5
    Private Const SB_BOTTOM = 7
    Private Const SB_TOP = 6

————————————-

Now all thats left is to setup and call the SendMessage API function…

The first parameter of the SendMessage call is the handle to your textbox control that you want to use.

The second parameter is to let the api know we want to perform some type of scroll action on the control.

The third parameter is the type of scroll to perform on the control.

The fourth parameter is Not used in this example.

————————————-

Visual Basic 5.0, 6.0 – Scroll the Textbox to the Bottom/Top…

        '
        'This will make the textbox scroll to the bottom without moving the cusor position.
        SendMessage TextBox1.hWnd, EM_SCROLL, SB_BOTTOM, 0
        '
        'The will make the textbox scroll to the top without moving the cursor.
        SendMessage TextBox1.hWnd, EM_SCROLL, SB_TOP, 0

Visual Basic.NET – Scroll the Textbox to the Bottom/Top…

 

        '
        'This will make the textbox scroll to the bottom without moving the cusor.
        SendMessage(TextBox1.Handle.ToInt32, EM_SCROLL, SB_BOTTOM, 0)
        '
        'The will make the textbox scroll to the top without moving the cursor.
        SendMessage(TextBox1.Handle.ToInt32, EM_SCROLL, SB_TOP, 0)

 

_____________________________________

Alright, those codes above should have moved your textbox control contents down to the bottom and up to the top. Also the cursors position will Not be moved like the other method would do. Hopefully this post will be liked alittle better. If not, then I don’t know what else you want and give up… 🙂

Jason

.NET Framework Library Source Code now available

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
 


  Well its been a somewhat long time coming, but Microsoft has released the source code for the new .NET Framework. IF you’ve ever wanted to see how Microsoft did something you saw in the Framework Classes and especially debugging, then this is your chance. At this time not all of the framework libraries (like Linq) is available. They plan to continue releasing more and more through the year.

The Framework source in this release and Debugging unfortunately requires Visual Studio 2008 NON-Express editions since you have to enable and setup .NET Source Access Control, which the Express Editions apparently do not support. To get more info on doing this simply go to this page.

But Scott said that the Framework Source Code WILL be downloadable as files on your local computer. That is actually what I am waiting for 🙂

Anyways, below is a small excerp…

——————————————————–

From the Microsoft Blog Post…

——————————————————–

  Last October I blogged about our plan to release the source code to the .NET Framework libraries, and enable debugging support of them with Visual Studio 2008.  Today I’m happy to announce that this is now available for everyone to use. Specifically, you can now browse and debug the source code for the following .NET Framework libraries:

  • .NET Base Class Libraries (including System, System.CodeDom, System.Collections, System.ComponentModel, System.Diagnostics, System.Drawing, System.Globalization, System.IO, System.Net, System.Reflection, System.Runtime, System.Security, System.Text, System.Threading, etc).
  • ASP.NET (System.Web, System.Web.Extensions)
  • Windows Forms (System.Windows.Forms)
  • Windows Presentation Foundation (System.Windows)
  • ADO.NET and XML (System.Data and System.Xml)

We are in the process of adding additional framework libraries (including LINQ, WCF and Workflow) to the above list. I’ll blog details on them as they become available in the weeks and months ahead.

——————————————————-

——————————————————-

IF your interested click on this link to the blog post. I will change/update my comments in this post if I find out I said something that isn’t accurate. Alrighty, Have Fun!

           Jason

MCI MultiMedia Command String Beginners Tutorial – A Step by Step Guide for Visual Basic

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (28 votes, average: 4.29 out of 5)
 

I originally made this article many years ago. I tried to keep the links up to date but not with possible changes to the MCI system or better techniques. Feel free to let me know if there is anything that can be changed or improved upon by leaving a comment.

Updated 2014, December 05th & 17th: Made some minor format and wording changes.

   Overview: I made this tutorial to help others learn to use the Windows MCI (Multimedia Command Interface) system to create their own media based features or full applications like a Music Player, Movie Player, CD Player (.cda), and so on. MCI is easy to use and is able to support many of the popular file formats. For instance, you can playback: MP3 files (.mp3), Wave files (.wav), Windows Media Audio (.wma), etc… on the audio side; and MPEG4 (.mp4), AVI Video (.avi), QuickTime(.mov), Windows Media Video (.wmv) etc… on the video side. Hopefully by the time you finish this article, you will have a better understanding of the MCI system.

  Visual Basic 6.0 and other Information: While this tutorial’s example source code is in VB .NET, the principles are the same for all languages actually. C#, C++, etc.. To make much of the .NET example code work in VB 6 just change “Integer” typed variables and parameters to “Long” types instead.

—————————————————————————————————–

Introduction

With this tutorial beginners will hopefully learn how to use the Windows MCI system via the MCISendString function available in the WinMM.dll. The article does not provide much in the way of source code for special tasks or features, but aims to teach someone how to make their own. I do have a few pre-made libraries which uses MCI to do many music/movie based functions at my vbcodesource.com website.

As mentioned earlier, MCI can play almost any media file available with the proper compression decoders available. For instance, you can play DVD Movie’s If a device provides DVD decoding assistance like some video cards or Windows has a software decoder available. Likewise you can play high definition H.264 videos if you have the proper H.264 codecs, DivX Movie’s if you have the DivX Codec installed or Apple QuickTime videos if you have the QuickTime codec installed, etc.. In this tutorial I will help you get a good understanding how to program and use the MCI Device system so you would have the ability to make your own media player or add media support to your applications. As for the exercise in this tutorial I will show you how to make a music player with a few basic features. I am pretty sure though, after you read and study this article you will be able to create your own music and movie player with ease.

—————————————————————————————————–

Lets get some Documentation

  Start out by going to: http://msdn2.microsoft.com/en-us/library/ms712587.aspx– website, then click on the: ‘Multimedia Command Strings’ link if it doesn’t go directly to that page. Go ahead and look over some of the documented MCISendString Commands available. For example: Click on the ‘open’ command at the left side of the webpage. Scroll down alittle on the right side of the page and you will see the documented device types and the device flags available for that device type. Scroll down alittle more and it will explain what the meaning of each device flag is for. For example: On the same ‘open’ page, scroll down till you find the waveaudio device listing. Look at the column to the right and you will see the available flags and the meanings that will work with the waveaudio device. Scroll down to the Value section listings of the page and find the ‘buffer buffer_size’ flag and look to the right and it explains what it is for and what it does. So, now that we’ve got that out of the way, lets get started with programming the Mci Device.

  Note: The mpegvideo device driver is not documented at the msdn webpage. We can still do quite alot with it since alot of the commands from the digitalvideo device and waveaudio device will work with the mpegvideo device. The MpegVideo device type would be the Device Driver of choice for most of our multi-media needs since it will play alot of the movie and music formats out there. The MCI system uses the functions from the ‘winmm.dll’ file. Winmm.dll is used for some of Windows own media programs.

—————————————————————————————————–

What is the mciSendString function?

The first step you will want to do is add:

    Private Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal uReturnLength As Integer, ByVal hwndCallback As Integer) As Integer
  • to the declarations section of our form. The return value of the mciSendString function will be a number. It will return different numbers for different errors or return a 0 if the command was successful.

Example: Say we made a variable;

        Dim retVal As Integer

 

We would use our mciSendString function in this manner…

retVal = mciSendString("Open " & filename & " alias movie", 0, 0, 0)
  • retVal would contain a number returned by our Mci Device to let us know what happened. More on that below. I will briefly go over each parameter of the mciSendString function.

The lpstrCommand parameter is a string that specifys the MCI command string and flag. In other words this parameter would be our command that we pass to the MCI Device. Like in our paragraph above, open would be a command string that we passed to the MCI Device. It tells the MCI Device to do something. The command string could also have flags associated with it. More on that below in the tutorial.

The lpstrReturnString parameter is a buffer that receives the return information if requested. Example: If we used the status command string and used the position flag, lpstrReturnString would contain the position information of the music or movie we are playing. We would just create a string variable with a character buffer.

Example:


        Dim returnData As String = Space(128)

ReturnData is now a String with a 128 Space buffer.

We would put ReturnData in the parameter and it will receive our position value.

The uReturnLength parameter is the size, in characters of the lpstrReturnString parameter. If we used

        Dim returnData As String = Space(128)

 

– for our lpstrReturnString parameter. Then the size we would put for the uReturnLength parameter would be 128 or you can put Len(ReturnData).

The hwndCallback parameter is not used in this article. It would contain the Handle to to a callback window if the Notify flag was used in our command string. Just set this parameter to 0 for now.

Note: If the command string does not request a value in the lpstrReturnString parameter then you can set the lpstrReturnString, uReturnLength, hwndCallback parameter to “Nothing” or set to vbNullString, 0, 0). More on that further in the tutorial. 

———————————————————————————————–

What is mciGetErrorString?

OK, the second step you would want to do is add:


    Private Declare Function mciGetErrorString Lib "winmm.dll" Alias "mciGetErrorStringA" (ByVal dwError As Integer, ByVal lpstrBuffer As String, ByVal uLength As Integer) As Integer

 

– to the declarations of the form. This is a very useful function for programming the Mci Device. This will convert the number returned by our retVal variable (from the mciSendString function) into something that we will be able to understand alittle more. It will give us a brief description of what happened. I will briefly go over each parameter in this function.

The dwError parameter will contain our return value from our mciSendString function.

Example:

Say we used retVal as our variable to recieve the return value of our mciSendString function. In the dwError parameter we would put in the RetVal varaiable.

The lpstrBuffer parameter will contain the string value of our dwError parameter.

Example: Say we had

        Dim GetError As String = Space(128)

 

If you put GetError in the lpstrBuffer parameter, then GetErrorwould receive the error string.

The uLength parameter is the character length of the dwError parameter.

Example: Say we used the above GetError string variable. We would create the string to have a buffer of 128 characters.

        Dim GetError As String = Space(128)

 

So, in the uLength parameter we would put 128 or you can put Len(GetError). Either way will work just fine.

 ———————————————————————————————–

How to Write your own Audio or Music Player

  Let start doing alittle MCI Programming by making a simple mp3/wave player. Put 4 command buttons, 3 labels, and a timer on the form. With the first command button name it btnPlay set the .Text property to “Play”, the second button name btnStop and set the .Text property to “Stop”, the third button, name it btnPause and set the .Text property to “Pause”, the fourth name btnClose and set the .Text property to “Close”; name one of the labels lblPosition and will be used for the position status, name the second label lblLength and will be used for the length, and the third name lblError will be used to give us our Mci error status(Make the label fairly big because it could have a long explanation.) The timer will give the position status of the music every second, so set the interval to 1000.

  Pretty much always the first step in programming the Mci Device is starting with the open command string, since it is where we select the device type we want to use and create the alias we want to use. So go to the webpage I stated at the beginning of this tutorial and find the ‘open’ command string and click on it to read the documentation. Look over our available flags. We will want to use 2 of the flags. The type device_type(note below) and alias device_alias(note below) flag. The next step you want to do is select the file you want to play. One annoying thing about the Mci Device is that it has a hard time with long filenames, so you will either have to convert the filepath and name to the shortpath of the file or a easier and recommended way is just putting quotes around your filepath and name. The way to do this is first select the file you want to play. Then wrap the filepath and name in quotes.

Example:

        Dim fileName As String = Chr(34) & "C:MP3 Musicmysound.mp3" & Chr(34)

 

That will wrap the filepath in quotations. ( Chr(34) is the code for ” *Quotes* ) Of course, change the path and filename to a music file you have on your computer. Each time you use the open command, you will want to put the quotes ” ” around the file you want to play. Ok, so now that we have selected the file we want to play and put the quotes around the path, lets start programming the Mci Device. Put this in the declarations section of our form.

        'Will store our return value from the mciSendString function.
        Dim retVal As Integer

        'This variable will contain the data from the lpstrReturnString parameter. It will have a 128 character buffer.
        Dim returnData As String = Space(128)

        'Will store our return string from the mciGetErrorString function. With a buffer of 128 characters.
        Dim errorString As String = Space(128)

        'Will contain True or False if our mciGetErrorString was successful at determining our error returned
        'from the mciSendString function.
        Dim errorSuccess As Boolean

 

In the btnPlay button put:

        'Replace the path and filename' with file that you have.
        fileName = Chr(34) & "C:MP3 Musicmysound.mp3" & Chr(34)

        retVal = mciSendString("open " & fileName & " type mpegvideo alias oursong", vbNullString, 0, 0)

 

O.k. Lets break this down. Our retVal variable will contain the return value of the ‘mciSendString command’. The open command will open our fileName using the mpegvideo device type and create a alias named oursong.

*Note: The type flag can be optional. The Mci Device is usually very good about auto-selecting the correct device driver of our specified file.

*Note Again: The alias flag can also be optional. I highly recommend using it so you don’t have to keep referring to your device by the fileName variable. Just use oursong to refer to our opened device. Or any other name to refer to the device.

To see if the Mci Device was successful lets call our mciGetErrorString function. In the same command button below the code we already put in add:

        errorSuccess = mciGetErrorString(retVal, errorString, 128)

 

O.k. Lets break this down. Our errorSuccess variable will contain the return boolean value of our mciGetErrorString function. It will contain either “True” if it was successful or “False” if it was not successful. The retVal variable we used contains the return value from our mciSendString function.

Lets get the description of our error if one was created. In the same command button type in:

        lblError.Text = "Error Status: " & errorString

 

Run the program and press the “Play” button. lblError should read “The Specified Command Was Carried Out.” That means that everything went smooth and is O.K.

Now goto the webpage again and find the close command string. In the btnClose button type:

        retVal = mciSendString("close oursong", 0, 0, 0)

        errorSuccess = mciGetErrorString(retVal, errorString, 128)

 

O.k. Lets break this down. You should already know what the retVal variable returns. So, I won’t go over that again. What the close command does is close either a specified device identifier(Alias) or you can close all device identifiers(Alias’s) by using the all flag. So, what we just told the Mci Device to do is close our oursong device from memory. Notice that the other 3 parameters are “0” zero? Well, since the close command does not return anything we can just set the parameters to “0”. You should already know what the mciSendErrorString does so I won’t go over that again.

Now run the program again and press the play button twice. lblError should now read “The specified alias is already being used in this application. Use a unique alias.” The error string returned should be self-explanatory, but I will explain it briefly. What its saying is that the oursong alias is already opened and is being used so if we wanted to open another Mci Device we need to supply a new alias. Now press the btnClose button. lblError should now read that “The Specified Command Was Carried Out.” That means that our close command was successful at closing our oursong from memory. Now press the play button and lblError should read “The Specified Command Was Carried Out.” Press the play button again and lblError should read that “The specified alias is already being used in this application. Use a unique alias.” If you press that “Close” button lblError should read that the command was carried through. If you press that “Play” button lblError should again read that the command was carried through. Blah.. Blah.. Blah.. O.k. enough of that stuff.

Now lets program the Mci Device to play our Mp3, Wave, ect. song. Go to the webpage and select the play command and look over it. Every device type recognizes the play command string. In the “Play” button between the mciSendString code and the mciGetErrorString code that we already put their type:

        retVal = mciSendString("play oursong", vbNullString, 0, 0)

 

O.k. Let break this down. The play command tells the Mci Device to start playing the file contained in the ‘oursong’ alias. Pretty simple. Run the program and press the “Play” button and it should start playing the song you specified in the ‘fileName’ variable. Everything should be going well. If it isn’t check the lblError Text and see what the mciGetErrorString function is returning. Maybe while you was looking at the documentation on the play command you noticed a from position flag and a to position flag. What these 2 flags do is allow you to start playing at a certain point in the file and play to a specified point in the file. If you want to play the complete file then just ignore these 2 flags. But if you want to specify a starting point and a ending point you would program the Mci Device in this manner. (You can also specify whether to start playing the song from a specified point to the end of the song, or tell it to start from the beginning but only to a specified point.)

        retVal = mciSendString("play oursong from " & 1000 & " to " & 3000, vbNullString, 0, 0)

 

O.k. Lets break this down. We told the Mci Device to play ‘oursong’ from “1000 milli-seconds” to “3000 milli-seconds”. Pretty simple right? Now that we have a play command and a close command, what if you just wanted to stop the song at its current playing position and not completely close the file? Well, thats where the ‘stop’ command comes in. Go back to the msdn documentation website and click on the ‘stop’ command. Notice that their is only 1 flag available and thats for digital devices? There are no other flags we need for this command. Lets write our stop command. In the btnStop button type:

        retVal = mciSendString("stop oursong", vbNullString, 0, 0)

 

O.k. Lets break this down. Well, theres not much to break down. Its pretty self-explanatory. What it will do is tell the Mci Device to stop playing ‘oursong’. Not really anything more to say.

What if you wanted to add a pause command to our music player? Nothing to it. Just go to our Mci documentation website and click on the pause command. Pretty much like our stop command it doesn’t have any special flags associated with it. Lets write our pause command. In the btnPause button type:

        retVal = mciSendString("pause oursong", vbNullString, 0, 0)

 

O.k. Lets break this down. The ‘pause’ command is simply telling the Mci Device to stop playing oursong at the current playing position. Pretty simple. What if you wanted to resume a song that you paused with the ‘pause’ command? Nothing to it. Just go to the website and click on the ‘resume’ command and look at the documentation. Just like our ‘pause’ command their are no special flags associated with the ‘resume’ command. Put another command button on the form and name it btnResume and set the .Text property to “Resume”. Lets write our code to resume the playing of oursong.

        retVal = mciSendString("resume oursong", vbNullString, 0, 0)

 

O.k. Lets break this down. It is just simply telling our Mci Device to ‘resume‘ playing from where it was paused at when we used our ‘pause’ command. Nothing to it huh?

O.k. Now you have some basic functionality for your music player. Now you may want to be able to track the current position that the music is currently playing at. No Problem. Go to our documentation website and click on the ‘status’ command string. Look around on that page you see a ton of flags available with this command string. If you look at the waveaudio device you will see a position flag. That is the one we want to use to get the current position of our song. Lets write some code for it. In the timer control put:

        retVal = mciSendString("status oursong position", returnData, 128, 0)

        lblPosition.Text = "Position: " & Val(returnData)

 

O.k. Lets break this down. you should already know what the retVal variable is for. The ‘status’ command is telling the Mci Device that we want to get the status of oursong. But to use the ‘status’ command we have to specify a flag. So, you will have to tell the Mci Device what status information to return. We specified the position flag so, it will return the current playing position of oursong. lblPosition will contain the position value. Noticed that I used Val(returnData) for the lblPosition .Text? I did it so that lblPosition will only contain the numbers in the ReturnData string and not the remaining spaces in the buffer. Getting the hang of it now? Lets get our Mci Device to do more.

Did you happen to wonder what time format the position flag was returning to us? Well, lets have the Mci Device tell us what the answer is. Looking at our documentation webpage you should still be at the ‘status’ command string documentation. Look under either the digital video or waveaudio device type. You will see that there is a time format flag. That is the flag that we will use to get the current time format the Mci Device is using. Just draw a command button on the form and name it btnTimeFormat set the .Text property to “Time Format:”. In the code window of that button type:

        retVal = mciSendString("status oursong time format", returnData, 128, 0)

        MessageBox.Show(returnData)

 

O.k. Lets break this down. We are passing the ‘status’ command string to the Mci Device and using the time format flag. This will tell the Mci Device to give us the current time format. We will get our answer by getting the value of our returnData variable. If you want you can just open the Mci Device by pressing the “Play” button and then press the “Time Format” command button. It will throw a Messagebox with the time format that the Mci Device is currently using. It most likely should say “milliseconds”. Still with me? Easier then you thought huh? What if you wanted the format in seconds? Well, the Mci Device doesn’t support returning the time format in seconds but you can easily do it yourself. 1000 milliseconds = 1 second. So, all you would need to do it create a variable to divide our Val(returnData) / 1000. The variable will contain the value in seconds. What if you wanted to get the length of the song? Well, that is just as easy as getting the position. In the “Play” command button right above our mciGetErrorString function type:

        retVal = mciSendString("status oursong length", returnData, 128, 0)

        lblLength.Text = Val(returnData)

 

O.k. Lets break this down. We are simply telling our Mci Device to tell us the length of oursong. Earlier we asked the Mci Device to give us the current time format and it returned “milliseconds”. So, that will be the format that our length will be returned in since we haven’t changed the time format. Can we change the time format? Yeps we sure can. Goto our Mci document page and click on the ‘set’ command string. Just like our ‘status’ command string the ‘set’ command string has a few flags available to use. The flag we want to use to change the time format would be none other than the time format flag. What you will find out though is some files, like mp3’s, the Mci Device only supports the “milliseconds” time format. If we use the mpegvideo device driver then the only available time formats would be “frames” and “milliseconds. Since we are playing music files we won’t be able to get a time format in “frames”, only “milliseconds”. If you only wanted to play wave files, for example, you could use the waveaudio device type and get the time format in “bytes”, “milliseconds”, and “samples”. I don’t think “milliseconds” is all that bad though. What else would you want to add to your music player?

Do you want to know if the music is currently playing? Would you like to change the position of the file in real time? How about a volume control? Want all 3? Well, lets get started and first write a simple function that will let our application know if it is playing or not. Write the code below in the form.

    Private Function playingStatus() As Boolean

        retVal = mciSendString("status oursong mode", returnData, 128, 0)

        If returnData.Substring(0, 7) = "playing" Then

            playingStatus = True

        Else

            playingStatus = False

        End If

    End Function

 

O.k. Lets break this down. We are going to use our playingStatus function to contain “True” or “False” depending on whether or not the Mci Device is playing. If you check out our documentation website and clicked the status command string. Then scrolled down you would find a mode flag available. If you read the description of the mode flag it tells you what value’s it would return. So, now to get the playing status we would just need to get the value that is stored in our ReturnData variable. But since our ReturnData variable is 128 characters long we only want to get the first 7 characters. If ReturnData contains “playing”(which is 7 characters long) then our Mci Device is currently playing and will put “True” in our playingStatus function. Other modes are available too. The device can return “stopped”, “paused”, “not ready”, ect. Right now we are only interested in checking our Mci Device to see if it is “playing” or not. Thats important for our changing the position code. Lets write that now. Put a Hscrollbar control on our form and name it posChange. Type this code in the “posChange_Scroll” sub:

        If playingStatus() Then

            ' The Mci Device is playing so play from.
            retVal = mciSendString("play oursong from " & (posChange.Value * 1000), vbNullString, 0, 0)

        Else

            ' TheMci Device is not playing so seek to.
            retVal = mciSendString("seek song to " & (posChange.Value * 1000), vbNullString, 0, 0)

        End If

 

O.k. Lets break this down. If you go to our documentation webpage and click on the play command string you will see a available flag named from. That is the command string and flag we will use to keep the file playing but at a position specified by our posChange.Value. If you go to our documentation website and click on the seek command string you will find a available flag named to. That is the command string and flag that we will use to move the position and but not start playing. Got that? To recap what I said above if oursong is already “playing” we will want to continue “playing” oursong but at the point in the file specified by our posChange control. So we will use the commandstringplay’ and use the flag ‘from’ to continue playing oursong “from” the position specified by our posChange control. Enough about that already. Lets move on. The Hscrollbar cannot contain a value larger than “32767”*. Since the time format of the Mci Device is in “milliseconds” and the total length of almost every song would be larger then “32767 milliseconds”* we must convert the “milliseconds” format to a smaller number. The useful and easy thing to do would be to convert it to “seconds”. So, we will set the .Max property of our Hscrollbar to equal the total length of the song in “seconds”. To do this. Let go back to the btnPlay button and type this code below our code that tells the Mci Device to “play“.

        'Get the length of the song in milli-seconds.
        retVal = mciSendString("status oursong length", returnData, 128, 0)

        'This will convert our “millisecond” value to a value in “seconds”
        'Remember that 1000 milliseconds will equal 1 second. 2000 milliseconds = 2 seconds and so on.
        posChange.Max = Val(returnData) / 1000

 

*Note; Update: Visual Basic.NET does NOT seem to have the .Max property of the scrollbars limited to a value of ‘32767’ as it was in VB 5.0, 6.0. So, it seems that you no longer need to worry about setting the above code up by converting the milli-seconds to seconds. It looks like it is now able to contains milliseconds with no overflow.

O.k. This should be fairly simple to understand. We are just telling the Mci Device to return the length of oursong. posChange.Max property will now contain the length in seconds (or milliseconds, its your choice as to how accurate you want to be able to change the position). We divided the number returned by our ReturnData variable by 1000 which would equal “seconds”. Got that? I hope so. Now if you go back and look at the code above to change the position you should understand it alittle more. I hope this helped you instead of confused you. I’m trying to thoroughly explain it so you will completely understand. Just as a reminder. If the code is not doing what you expected and you want to find out what is going on use the mciGetErrorString function. O.k. Enough on this. Lets do one last thing that would be useful for a basic music player. Lets create a volume control. Put a Vscrollbar control on the form and name it volScroll and set the .Max value to “1000”. “1000” is the max for the volume. “0” is the minimum. Then go to our documentation webpage and click on the setaudio command string. Look over the available flags and you will find a volume to flag. That is the command string and flag we will want to use. So in the volScroll _Scroll sub put in this code.

        retVal = mciSendString("setaudio oursong volume to " & volScroll.Value, vbNullString, 0, 0)

 

O.k. This should be pretty simple to understand. We are simply telling our Mci Device to set the volume of oursong to the current value of the volScroll control. Thats it for a music media player with basic features! Check out my examples and libraries at www.vbcodesource.comwebsite.

Below is the final product…

 

Conclusion

 

  I hope this tutorial we went over gave you a nice understanding of how to program the Windows Mci Device. As you can see there are quite a few commands and flags available to do almost anything you want in a Movie or Music player. You could “turn of the left audio channel”, “set the volume for the right audio channel”, “you could open and close the cd door”, “change the speed at which the movie or music plays at” and much more. You should be able to decide what features you want and program the Mci Device yourself and have it do it for you. Remember to use the mciGetErrorString function as it is very useful. It tells you if the device understood what you told it to do, if the Device Type that you are using supports that command string, and much more. Bookmark the msdn webpage I gave you: http://msdn2.microsoft.com/en-us/library/ms712587.aspx – so you can have it as a good reference to see what command strings and flags are available. Reference – http://www.vbcodesource.com – Have Fun!

              Jason

How to Create Custom/Abnormal Shaped Forms in VB 6.0

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 4.00 out of 5)
 


  A earlier article showed how to change the shape of a form in .net based VBs. Unfortunately VB 6.0 (Classic Versions, Pre DotNet versions) does not have native support for Region based changes in the Form. Thankfully Microsoft added some API calls in Windows 98 and above that you can use to create custom/abnormal form shapes/regions. This article will show how to create a Elliptic Form Shape. But I will include the APIs to create the basic shapes below…

  • Elliptic Shaped
  • Round Shaped
  • Polygon Shaped

Below are the API Codes required to get this done.

     

———————————————————

 



    Private Declare Function SetWindowRgn Lib "user32" (ByVal hWnd As Long, ByVal hRgn As Long, ByVal bRedraw As Boolean) As Long

    Private Declare Function CreateEllipticRgn Lib "gdi32" (ByVal X1 As Long, ByVal Y1 As Long, ByVal X2 As Long, ByVal Y2 As Long) As Long

    Private Declare Function CreateRoundRectRgn Lib "gdi32" (ByVal X1 As Long, ByVal Y1 As Long, ByVal X2 As Long, ByVal Y2 As Long, ByVal X3 As Long, ByVal Y3 As Long) As Long

    Private Declare Function CreateRectRgn Lib "gdi32" (ByVal X1 As Long, ByVal Y1 As Long, ByVal X2 As Long, ByVal Y2 As Long) As Long

    Private Declare Function CreatePolygonRgn Lib "gdi32" (ByVal lpPoint As Any, ByVal nCount As Long, ByVal nPolyFillMode As Long) As Long

 
———————————————————

 

Now you simply need to make a variable to recieve the handle to the newly setup region…
 

        '
        'Will hold the handle to the new region.
        Dim hRegion As Long
        '
        'Below is the code to create a basic elliptic region…
        '
        'Create an Elliptic Shaped Region.

        hRegion = CreateEllipticRgn(0, 0, 100, 200)

  

Now that a new region has been created, simply call the SetWindowRgn Function passing the handle to the Form you want to change the shape in the first parameter. The other parameters are for setting up the elliptic shape on how your want it to look.

 

        '
        'Change the Form to the new region shape.
        SetWindowRgn(frmRegion.hWnd, hRegion, True)

 

 

———————————————————
 

  Thats all there is to it! Easy to use APIs makes it possible to do custom form regions using the WindowRgn based functions that are available in Windows 98 and Above. As usual I do have a example for Visual Basic 6.0 at my http://www.vbcodesource.com website. Have fun!

                    Jason

Using Chr() Code to Add Quotes to a Value in Visual Basic and VB.NET

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (9 votes, average: 4.33 out of 5)
 

At one time or another you may want to use quote characters ” ” as a value.  Since VB views quotes as containing the value, you would need to add multiple quotes around quotes to add quotes (huh?) to be a value. To me doing multiple quotes like that can be alittle tricky and look cluttered. Below is a example to add quotes around a string value doing it the multiple quotes way…

Dim str As String

str = """Quotes!"""

There is a better/easier way to do this (at least to me 🙂 ). It is a simple little feature that is available in All versions of Visual Basic and Visual Basic.NET, the Chr(ChrCode) Function.

Public Function Chr(ByVal CharCode As Integer) As Char

This little function will return the specified ChrCode Integer as its mapped character value. Chr$ coding is very easy to do. The codes below will add literal quotes to a string value…


Dim str AsString 

str = Chr(34) & "Quotes!" & Chr(34)

To me, the Chr version looks better and is easier to read. It would be more apparent as you concatenate (link) strings together with quotes. There are many more scenerios for Chr like using ChrCode #13 which will mimick the Enter/Return key. I may going over Chr Code more later on. Have fun 🙂

 

Jason

Using DoEvents() in Visual Basic and .NET the Right way!

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (4 votes, average: 4.75 out of 5)
 

The DoEvents() method is well known and available in VB 6.0 and VB.NET. Its often used in longer running, processor intensive code. It tells Windows to process the messages in the program’s message queue. That can help keep your program from appearing frozen and allows user interaction while the CPU is still busy executing the high usage code.

(In VB 6.0 and Older DoEvents() is a Function | In .NET and Newer its a Subroutine)

Unfortunately there is a tradeoff when using DoEvents. That tradeoff is ‘Performance’. The more you call DoEvents, the more CPU cycles are taken away from your intensive code to process the message queue. Thankfully, there is a way to help offset much of the performance loss and still allow your program to be responsive. That’s by using the GetInputState() function in the User32.dll library.

[Note:

Most of the code in this article is from an example I made at www.vbcodesource.com.

It runs 3 different scenarios with benchmark data for each of them.

Scenario One: is executing a CPU intensive loop Without using DoEvents().

Scenario Two: is executing the loop using DoEvents() with the GetInputState() API call.

Scenario Three: is executing the loop using Only the DoEvents() method.

End Note]

Windows API to the Rescue

What’s nice about the GetInputState() function is you can use it to First Check if there are any messages in the calling thread’s queue that is waiting to be processed. Below is the declare for that function…

Visual Basic 6.0
'
'This call will see whether or not there are any messages waiting
'to be executed in the calling thread.

    Private Declare Function GetInputState Lib "user32" () As Long

Visual Basic.NET
'
'This call will see whether or not there are any messages waiting
'to be executed in the calling thread.
    Private Declare Function GetInputState Lib "user32" () As Int32

—————————————————

This function is very simple to use. Just simply get its return value to see if any mouse and/or keyboard messages needs processed…

'
'You save ALOT of time by using the GetInputState api call to check
'whether any messages needs to be processed first. The DoEvents()
'method is ONLY fired when there ARE messages that needs to be processed,
'thus really increasing the performance of your application.

'If it returns 0, then there are NO keyboard or mouse messages queued in the thread.

  If Not GetInputState = 0 Then Application.DoEvents()

—————————

Performance Results

In the Example I was talking about earlier I made a simple cpu intensive Loop and benchmarked each of the three scenerio’s.

  NO Doevents – 0.011106160…. Seconds.

  Doevents WITH GetInputState – 0.397925155…. Seconds.

  Doevents ONLY – 8.273245901…. Seconds.

As you can see there are definitely performance/speed differences between each scenario. Of course No DoEvents() will be the highest performing scenerio but at the cost of freezing your application until the code has finished executing. But compare DoEvents() With GetInputState to DoEvents Only. Those are very noticeable differences in performance between the two methods. Simply checking the queue first by using GetInputState() increased performance MANY Times in that test. And as you already know by doing so you will Stop your application from freezing which will allow the user to interact with your application even when your running heavy cpu intensive code.

Anyways that’s all, I hope you got something of use from this tip. Take care… 🙂

 

Jason

How to get the ShortPathName of a LongPathName in VB and VB.NET

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 4.00 out of 5)
 

There could be a time when you may need and/or want to convert a path to its ShortPath name alternative. Some APIs may even recommend you use the Short Path representation of the normal long path name. To convert a long path to a short path name is very easy to do thanks to a little Microsoft API call function. The function is called: GetShortPathName() and as the name suggests, will convert the path in the parameter to it short Path equivalent.   To get started you will want to put the API Function in your project. I usually just place it near the top of the code in the declaration section.

_____________________________________________________

Visual Basic 5.0/6.0 Version…

Private Declare Function GetShortPathName Lib "kernel32" Alias "GetShortPathNameA" (ByVal longPath As String, ByVal shortPath As String, ByVal shortBufferSize As Long) As Long

Visual Basic.NET 2002/2003 and Visual Basic 2005/2008/2010 Version…

Private Declare Function GetShortPathName Lib "kernel32" Alias "GetShortPathNameA" (ByVal longPath As String, ByVal shortPath As String, ByVal shortBufferSize As Int32) As Int32

And now you just need to call that function with your data in the parameters. Example is below for Visual Basic Classic (5.0/6.)…

'
'The path you want to convert to its short representation path.
Dim longPathName As String

longPathName = "C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705"
'
'Get the size of the string to pass to the string buffer.
Dim longPathLength As Long

longPathLength = Len(longPathName)
'
'A string with a buffer to receive the short path from the api call…
Dim shortPathName As String

shortPathName = Space$(longPathLength)
'
'Will hold the return value of the api call which should be the length.
Dim returnValue As Long
'
'Now call the function to do the conversion…
returnValue = GetShortPathName(longPathName, shortPathName, longPathLength)

MsgBox(shortPathName)

 

Now for the Visual Basic.NET 2002/2003/2005/2008/2010 Code Version…

 

'
'The path you want to convert to its short representation path.
Dim longPathName As String = "C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705"
'
'Get the size of the string to pass to the string buffer.
Dim longPathLength As Int32 = longPathName.Length
'
'A string with a buffer to receive the short path from the api call…
Dim shortPathName As String = Space(longPathLength)
'
'Will hold the return value of the api call which should be the length.
Dim returnValue As Int32
'
'Now call the function to do the conversion…
returnValue = GetShortPathName(longPathName, shortPathName, longPathLength)
 
MsgBox(shortPathName.ToString)  

 
_____________________________________________________
 

Thats all there is to it! The new ShortPathName from the Long path in the example code above returns the path as: “C:\WINDOWS\MICROS~1.NET\FRAMEW~1\V10~1.370”

So if you’ve been needing a way to get a short path of a long path, this code should do it for you just fine… 🙂

Jason

Microsoft is giving you a peek at the source code for the .NET Library!

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
 

Update: I made a couple changes to the post for accuracy reasons as I learned them..

You may have already heard a couple days ago that Microsoft is making the source code to the DotNETFramework available for developers to download via a Reference License… Although they will only release a limited amout of the librarys at this time, they plan on releasing more and more as time goes on.

Below is a small excerp…

  Today I'm excited to announce that we'll be providing this with the .NET 3.5 and VS 2008 release later this year.We'll begin by offering the source code (with source file comments included) for the .NET Base Class Libraries (System, System.IO, System.Collections, System.Configuration, System.Threading, System.Net, System.Security, System.Runtime, System.Text, etc), ASP.NET (System.Web), Windows Forms (System.Windows.Forms), ADO.NET (System.Data), XML (System.Xml), and WPF (System.Windows).  We'll then be adding more libraries in the months ahead (including WCF, Workflow, and LINQ).  The source code will be released under the Microsoft Reference License (MS-RL).You'll be able to download the .NET Framework source libraries via a standalone install (allowing you to use any text editor to browse it locally).  We will also provide integrated debugging support of it within VS 2008.

More from the post…

  Having source code access and debugger integration of the .NET Framework libraries is going to be really valuable for .NET developers.  Being able to step through and review the source should provide much better insight into how the .NET Framework libraries are implemented, and in turn enable developers to build better applications and make even better use of them.

There are advantages to this release and debugging being one of them. I will post more info on this as I learn it. Check out this link for the actual post…

Jason

Extract/Return the file Path and Filename without the Extension using VB.NET

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (4 votes, average: 4.50 out of 5)
 

This will take a file path, extract and return the filesystem path along with the filename but WITHOUT the extension.

        Dim filePath As String = "c:\MyDirectory\MYFile.txt"

        Dim extensionPosition As Integer = filePath.LastIndexOf(".")

        Dim filePathNoEx As String = filePath.Substring(0, extensionPosition)

        MsgBox(filePathNoEx)

 

Allow only certain characters in a textbox using VB 6.0

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
 

Shows how to use Visual Basic 6.0 (VB 5.0 as well) to only allow certain, specific characters in a textbox control.

        '
        '1 textbox ‘put in keypress procedure of textbox
        '
        Const Numbers$ = "0123456789."

        If KeyAscii <> 8 Then

            If InStr(Numbers, Chr(KeyAscii)) = 0 Then

                MsgBox("error")

                KeyAscii = 0

                Exit Sub

            End If

        End If

Check if your Application is Already Running in VB 6.0

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
 


'vb 5/6

If App.PrevInstance Then

MsgBox(“Program is already running.”)

Exit Sub

End If

How to Check if Directory Exist in Visual Basic 6.0

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
 

This shows how to use VB 6.0 to check whether or not a directory exists.

'Visual Basic 6.0 and VB 5.0
 
Dim f As String

f = "C:\WINDOWS"
 
dirFolder = Dir(f, vbDirectory)
 
If dirFolder <> "" Then
 
    MsgBox(“This folder already exists.”, vbCritical) 


    'directory exists action here
 
End If

How to Delete a File using VB 6.0

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
 

This will completely delete a file from the hard drive using Visual Basic 6.0. This will permanently delete the file! It will NOT send it to the recycle bin.

        Dim fileToDelete As String

        fileToDelete = "c:\somefile.file"

        Kill(fileToDelete)

Paste Text from the Clipboard in Visual Basic 6.0

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
 

This will paste text from a textbox to the Windows clipboard using VB 6.0

 


Text1.SelText = Clipboard.GetText
 

 

How To Print a Composite Image From a RichTextBox by using VB 6.0

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
 

This article demonstrates how to print composite images (Text and Graphics) from a RichTextBox Control. It uses Visual Basic 6.0

 Click here to go to the Microsoft page

            Jason

Check if the Computer is Connected to a Network using VB.NET 2005 and Higher

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
 

How to check if a computer is connected to a network or not.

‘Check if the computer is connected to the network. 
MsgBox(My.Computer.Network.IsAvailable)