Archive for the '- (.NET All + 05/08)' Category

Free VB Icons and Image Resources! | Updated – July 23rd, 2012

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

 

For sure Icons/Images can really make your Visual Basic 6.0 and Visual Basic.NET applications stand out and shine. Unfortunately alot of the Icons you find either cost money and/or will not allow you to use them in a commercial based application. So that is where this little post comes in. I will continue to add free VB icons sources as they are found.

Note: While Visual Basic 5.0/6.0 and Visual Basic.NET 2002/2003 may come with icons, and VB 2005/2008 as well, you might want something alittle more unique.

Starting below are Free VB Icons and Visual Basic.NET icons sources

_______________________________

Added 07-23-2012

Icon Search Engine- This site has a very nice collection of icons for you to search. I found many icons in many different formats like tiff, and png. Even Transparent icons as well. Very simple to download without a ton of add or restrictions. Very few ads you have to wade through before you get to what your looking for!

Free VB Icons at Icon Site Search webpage

Added 08-27-2010

Icon Archive - There are quite a few Icons available at this site. It has a huge mixture of Completely Free-Royalty Free icons, Free for Non-Commercial, and Pay Icons. The site is organized pretty well and is easy to get the icon you want. Just remember to look at the license to decide if the license will fulfill your needs or not. Be sure to check out the rest of this page. Enjoy!

Added 06-12-10

FREE Stock Icons - This site has a huge list of icons that are not only Free but is also Royalty Free (RF, Basically means you don’t have to pay them anything if they are used in a money making application or whatever.). The free versions has possible limited image sizes and file formats. All of the free images are at least jpeg which is a perfectly fine format for most people. You can easily convert them to .ico if you want. If you want many different sizes and multiple image formats you can Sign-Up for a account for a certain fee depending on what kind of access you want. Still the 100% free icon images were good quality and had a few different sizes and came in jpeg and .png formats. Most sizes has a Watermark but I think the 48×48 has no Watermark at all and is fully compatible and free  for your applications! The ones I downloaded at least…

Simple screenshot of the website for free VB icons

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

FamFam Mini Icons - These are about 144 various icons that you can use for ANY purpose. Completely royalty FREE and are actually good quality as well.

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

FamFam Flag Icons - This link has alot of various Flag based icons and images. These are completely Royalty FREE and you can use them in ANY type of application, whether its free, shareware or even commercial.

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

FamFam Silk Icons - These are probably close to the BEST Icons you can get that are COMPLETELY FREE with absolutely NO limitations and Royalty Free. He has available more than 700! 16×16 Icons in the download. High Quality as well!

Note: If you find these FamFamFam based icons useful and you want to support him in his work. It would be good if you could send him any amount, especially since he lets you do whatever you want with his icons. He has a link to donate on most of the download pages.

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

Farsight Icon Pack by deviantART - While they do not cost anything, the license does NOT allow them to be used in a commercial based application.

There are alot of other various free VB icons and images at deviantART as well. Click here to goto the main page…

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

I will add more Free VB Icons and/or Image sources when I continue to find more. I do hope you found some icons you can use. Have fun!

Jason

Visual Studio 2012 RC1 (Visual Basic 11-2012) – plus Two Free 2010 EBooks

 

Update: June 5th, 2012 – Microsoft has now updated the release to Visual Studio 2012 RC1 (Release Candidate 1). The main links below will take you to the VS 2012 download pages.

Original info Below…

Microsoft released the latest version of Visual Basic/Visual Studio 2011 as a Beta download a while back. If your interested, below are the basic requirements to run the beta. Also below is the webpage to download the the web-installer or Visual Studio .ISO image which will include all of the major languages like VB 2011, C#, ect… Below that is the link to get your two free ebooks based on Visual Studio 2010: One is: Moving to Visual Studio 2010 and the other is: Programming Windows Phone 7. They have been available for quite a while but I figured I would link to them anyways.

Here is the main page to download either the web installer or the complete ISO image.

System Requirements

Supported Operating Systems•Windows 7 (x86 and x64)
•Windows 8 Consumer Preview (x86 and x64)
•Windows Server 2008 R2 (x64)
•Windows Server 8 Beta (x64)

Supported Architectures
•32-bit (x86)
•64-bit (x64)

|

Hardware Requirements•1.6 GHz or faster processor
•1 GB of RAM (1.5 GB if running on a virtual machine)
•10 GB of available hard disk space
•5400 RPM hard drive
•DirectX 9-capable video card running at 1024 x 768 or higher display resolution

Yep you probably guessed it. Doesn’t look like neither Vista or Windows XP is going to be able to use, at least the Beta version. Which is a shame for me because I use Vista 64 and like it over all the Microsoft operating systems.

Beta Links below….

 

Click here for the 2011 Beta Professional Edition

Click here for the 2011 Beta Express Editions

Click here for the 2011 Beta Standalone Download Page

________________________________________

Click here to get the Free E-book – Why Upgrade to Visual Studio 2010

Why upgrade to Visual Studio 2010?

For a limited time, you can download two free e-books from Microsoft Press: Moving to Visual Studio 2010 and Programming Windows Phone 7. Moving to Visual Studio 2010 takes you through the new features and characteristics of Visual Studio 2010 as compared to previous versions of Visual Studio, including Visual Studio.NET 2003, Visual Studio 2005, and Visual Studio 2008.

Click here to get the Free E-book – Microsoft Press EBook – Programming Windows Phone 7

Overview - Develop your first applications for Windows Phone 7 using Microsoft XNA and Silverlight—expertly guided by award-winning author Charles Petzold. This book is a gift from the Windows Phone 7 team and Microsoft Press to the programming community.

__________________________________________

I was planning to post this weeks ago just a few days after the 2011 Beta release, but I forgot to do so. Still, hopefully someone out there will find this post useful. :)

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

 

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

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

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

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

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

 

Here starts the code.

'The Simple Mail Tranfer Protocol client with the Host and Port number to use. You will
'want to change these settings to what you need to use. The host, smtp.gmail.com and port
'587 will work if you use a gmail account.
Dim smtp As New System.Net.Mail.SmtpClient("smtp.gmail.com", 587)

'This will contain the actual message data to send.
Dim eMailmessage As New System.Net.Mail.MailMessage

'Used to setup the eMail as an html view.
Dim htmlView As AlternateView

'Used to setup the mail to have a plain text view.
Dim plainTextView As AlternateView

'Will temporarily hold the text for the html message view.
Dim theHtmlMessage As String

'This variable will temporarily hold the plain text format view.
Dim thePlainMessage As String

 

Now you need to setup your credentials and the Secure Sockets Layer (SSL) property. The Secure Sockets Layer, or Ssl property, is to be set to True for many smtp (Simple Mail Transfer Protocol) providers. It is required for Googles Gmail, Microsofts Hotmail, Office Live Mail, and even Yahoo mail.


'Use Secure Socket Layer to Encrypt the connection for sending the mail. This needs
'be set to "True".
smtp.EnableSsl = True

'Setup the gmail host.
smtp.Credentials = New System.Net.NetworkCredential("gmailLoginName@gmail.com", "gmailLoginPassword")

 

Now setup the basics of your email like the recipient(s), subject, and so on…


eMailmessage.Subject = "Check out my email message!"

eMailmessage.From = New Mail.MailAddress("you@hotmail.com, "Jason")

eMailmessage.To.Add("ToPerson@yahoo.com)

 

The next code is the contents of your email message. One will be the body content for the html format view, and the other is the contents for the text based view.


theHtmlMessage = "<strong>This is Html!</strong><br/><br/><u>This is Html as well!</u>"

thePlainMessage = "This is only plain text! No html formatting!"

 

Now that both the plain text and html message is in a string variable its time to add them to the AlternateView Class as a string itself using the CreateAlternateViewFromString function.


        'Setup the mail message as an html view.
        Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString(theHtmlMessage, _
            Nothing, MediaTypeNames.Text.Html)

        eMailmessage.AlternateViews.Add(htmlView)

        'Setup the mail message as an plain text view.
        Dim plainTextView As AlternateView = AlternateView.CreateAlternateViewFromString(thePlainMessage, _
            Nothing, MediaTypeNames.Text.Plain)

            eMailmessage.AlternateViews.Add(plainTextView)

 

As you can see, its quite easy to setup your mail message to have available alternate views. Just simply use the CreateAlternateViewFromString function and pass your message as html in one view and plain text in the other view. Now all thats really left is to send your email message to the recipient that you specified in the earlier source code.


'When you are done with setting up your email and your alternate view, then you just need
'to send your message.
smtp.Send(eMailmessage)

 

_______________________________

 

Thats all there is to it! So, after its all said and done, go ahead and get quite creative with your email messages using html, but always remember that it would be a good idea to also create a basic text email in case the persons mail client doesn’t support html so the recipients can still view your email message. Thats all for Part 2. I’m not exactly sure about Part 3 but it will probably go over sending your email messages to muliple recipients and carbon copys (cc) to other recipients as well. Have Fun!

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

 

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

 

Page UP

Page Down

Line UP

Line Down

Top Edge

Bottom Edge

 

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

 

_________________________________

 

To accomplish these features I will use the Windows API for most tasks. Specifically the Send Message Function is used. Below is the declaration for Visual Basic 6.0 (same for VB 5.0 as well) and VB.NET. All versions of .NET is supported, even the latest VB 2005, VB 2008, and Visual Basic 2010 versions. You shouldn’t have to change anything from the DotNet codes in this article.

 

Visual Basic 6.0


    'Used to Send Messages to the 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

 

Visual Basic.NET 2002/2003, VB 2005, VB 2008 and Visual Basic 2010

    'Used to Send Messages to the 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

 

_________________________________

 

Now for some Constants…

 

Visual Basic 6.0…


    Private Const EM_SCROLL = &HB5

    Private Const SB_PAGEDOWN = 3

    Private Const SB_PAGEUP = 2

    Private Const SB_LINEUP = 0

    Private Const SB_LINEDOWN = 1

    Private Const SB_BOTTOM = 7

    Private Const SB_TOP = 6

 

Visual Basic.NET through VB 2008 and VB 2010…


    Private Const EM_SCROLL As Int32 = &HB5

    Private Const SB_PAGEDOWN As Int32 = 3

    Private Const SB_PAGEUP As Int32 = 2

    Private Const SB_LINEUP As Int32 = 0

    Private Const SB_LINEDOWN As Int32 = 1

    Private Const SB_BOTTOM As Int32 = 7

    Private Const SB_TOP As Int32 = 6

 

_________________________________

 

Now all thats really needed is to call the sendmessage api with the right combination of constants to perform the intended function on your textbox control.

 

_________________________________

 

NOTE: If your using VB 5.0 or VB 6.0 then change some small things below…

Change – txtControl.Handle.ToInt32 to txtControl.hWnd

Change – Unless your getting the SendMessage functions return value then remove the parentheses which are the ( and ) characters.

Thats basically the only changes that are needed.

 

_________________________________

 

Page UP / Page Down

        
        'Move the cursor position up one page.
        SendMessage(txtControl.Handle.ToInt32, EM_SCROLL, SB_PAGEUP, 0)

        
        'Move the cursor position down one page.
        SendMessage(txtControl.Handle.ToInt32, EM_SCROLL, SB_PAGEDOWN, 0)

 

Line UP / Line Down

        
        'Move up by one line.
        SendMessage(txtControl.Handle.ToInt32, EM_SCROLL, SB_LINEUP, 0)

        
        'Move down by one line.
        SendMessage(txtControl.Handle.ToInt32, EM_SCROLL, SB_LINEDOWN, 0)

 

Go to Top Edge / Go to Bottom Edge

        
        'The will make the textbox scroll to the top without moving the cursor.
        SendMessage(txtControl.Handle.ToInt32, EM_SCROLL, SB_TOP, 0)

        
        'This will make the textbox scroll to the bottom without moving the cusor.
        SendMessage(txtControl.Handle.ToInt32, EM_SCROLL, SB_BOTTOM, 0)

 

Below is another method of scrolling the textbox to the Top and Bottom. But this WILL move the caret from its current position. The API method will NOT change the caret position. So using the code below depends on whether your ok with the cursor changing positions or not.

 

Scroll to Top with Cursor / Scroll to Bottom with Cursor

        '
        'Scroll the textbox to the Top.
        '
        'Set the cursor to the first character in the textbox which will be at the top of the 
        'control.
        TextBox1.SelectionStart = 0
        '
        'Make the textbox scroll to the actually caret postition.
        TextBox1.ScrollToCaret
        '
        '
        'Scroll the textbox to the Bottom.
        '
        'Set the cursor to the last character in the textbox which will be at the bottom of the 
        'control.
        TextBox1.SelectionStart = TextBox1.TextLength
        '
        'Make the textbox scroll to the actual caret postition.
        TextBox1.ScrollToCaret

 

_________________________________

 

These 6 features can really add alittle extra control to your custom notepad program, wordpad program, or any program I guess. As you can see its pretty simple to add. Thats all for Part #2. Have fun!

Jason

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

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

 

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

 

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

 

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

 


    'The Simple Mail Tranfer Protocol client with the Host and Port number to use. You will
    'want to change these settings to what you need to use. The host, smtp.gmail.com and port
    'will work if you have a gmail account.
    Dim smtp As New System.Net.Mail.SmtpClient("smtp.gmail.com", 587)


    'This will contain the actual message data to send.
    Dim eMailmessage As New System.Net.Mail.MailMessage

    
    'Will contain the attachment info to send with the message.
    Dim attachToMsg As System.Net.Mail.Attachment

 

Now that the main dimension code is done its time to setup your mail message.

 

        'Use Secure Socket Layer to Encrypt the connection for sending the mail. This needs
        'be set to "True".
        smtp.EnableSsl = True

        'Setup the gmail host.
        smtp.Credentials = New System.Net.NetworkCredential("gmailLoginName@gmail.com", "gmailLoginPassword")

 

You can now set the email’s Body/Text, Subject, From/Sender, and Recipient.


            eMailmessage.Subject = "Check out my attachments!"

            eMailmessage.Body = "I hope you got all of my attachments in this email!"

            eMailmessage.From = New Mail.MailAddress("you@hotmail.com, "Jason")

            eMailmessage.To.Add("ToPerson@yahoo.com)

 

Now before you send your email to the recipient, its time to setup and add more than a single attachment to your message. As you will see adding more than 1 attachment to your message is easy. I am using a OpeFileDialog to open a dialog window to select multiple files. Once the Dialog’s Open button is clicked then I will add all of the Filenames that was selected in the Open Dialog object.

 


        'Create a openDialog object to be able to select a attachment to the mail message.
        Dim openDLG As New OpenFileDialog

        'openDLG.AddExtension = True
        openDLG.ReadOnlyChecked = True
        openDLG.Multiselect = True
        openDLG.Title = "Select the file(s) you want added to the message..."
        openDLG.Filter = "All Files (*.*)|*.*"

        If openDLG.ShowDialog = Windows.Forms.DialogResult.OK Then

            For Each item As String In openDLG.FileNames

                'Create a new System.NET.Mail.Attachment class instance for each file.
                attachToMsg = New System.Net.Mail.Attachment(item)

                'Then add the attachment to your message. You have to do this everytime you run the code
                'above.
                eMailmessage.Attachments.Add(attachToMsg)

            Next

            Msgbox "I have finished adding all of the selected files! You can do more if you want!"

        End If

 

As you can see, adding multiple attachments to an email is very simple. Now all thats left to do is send your message to your recipient(s).

 


            'When you are done with setting up your email and add your attachments then you just need
            'to send your message.
            smtp.Send(eMailmessage)

 

Thats all there is to it! Do remember though that attachment sizes can add up very quickly. Before fully sending your email, it has to upload every file you attached to the message. So just remember that it could take awhile before its sent to the smtp server for processing. I advise you to use the smtp.SendAsync method to send your email since it will execute the resources for sending the email on a new thread seperate from your applications thread. Otherwise you will have to wait for the mail process to complete before you can continue using your application. I plan on adding a couple more parts in the near future. I plan on showing how to use a class I found that will easly convert rtf code to html code that allows you to use a richtextbox for the body of the email message and make it so the email will look very similar to how it looked and was formatted in the richtextbox control. I also plan on showing how to send an email with Alternative Views so that way you can send your email with different formats like Plain Text and Html and so on which allows the mail reader to pick which view would be best. Anyways, Have Fun!

Jason

How to Play Embedded Resource Wav Sound in VB.NET 2005, VB 2008, and Visual Basic 2010


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(bites?) 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.
 
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 and higher since I am using the SoundPlayer class. That class was not added until VB 2005. Visual Basic .NET 2002 and VB.NET 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
 
You access the resource manifest through the: Reflection.Assembly.GetExecutingAssembly namespace. You have to provide the name of your programs assembly and the name of your wave file. The name of my example project is: ‘playEmbeddedWaveFileEx’ and the name of my .wav file is: ‘waveFile.wav’. Remember that your assembly and wav file IS CASE Sensitive. In other words, each letter has to be the exact upper casing and lower casing that your actual assembly and wave file is. So for my example, you would pass the assembly and wave file as: ‘playEmbeddedWaveFileEx.waveFile.wav’. Notice the . or period seperating the assembly name and the name of the wave file. An easy way of getting your assembly name is using this Property: My.Application.Info.AssemblyName. First is the code for literally specifying the name of your assembly. So you pass it to the GetManifestResourceStream’s parameter like below…
 
Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream(“playEmbeddedWaveFileEx.waveFile.wav”)
 
BUT a better way…
 
Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream(My.Application.Info.AssemblyName & “.waveFile.wav”)
 

Now all you have to do is create a new SoundPlayer or access the Soundplayer under the ‘MY’ interface and pass the stream and simply start playing the wavefile like below…
 

        '
        'This creates a new instance of the SoundPlayer class while passing the stream the wave file
        'is embedded in.
        '
        Dim audioPlayer As New Media.SoundPlayer(Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream( _
            My.Application.Info.AssemblyName & ".waveFile.wav")) ' "playEmbeddedWaveFileEx.waveFile.wav"))

        audioPlayer.Play()

 
OR you can use the MY Interface…
 

        '
        'This code uses MY, which basically makes it a touch easier since you want have to create
        'a instance of the SoundPlayer class.
        '
        My.Computer.Audio.Play((Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream( _
            My.Application.Info.AssemblyName & ".waveFile.wav")), AudioPlayMode.Background)

 
___________________
 
Remember that I have a example program on how to perform the steps in this article. Click here to download.

OK, so playing embedded wave files isn’t as straight forward perhaps as it should be. I think I found out about using the GetManifestResourceStream at vbforums.com. If you know of something better definitely leave a comment. Either way, the code I provided here DOES work. At least for me. :) Have fun!

Jason

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

Various Listview Control tasks for Visual Basic.NET, VB 2005, VB 2008, Visual Basic 2010, and VB 2012.


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

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

 

Sorting Items…

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

Sorting Items – Ascending

            Listview1.Sorting = SortOrder.Ascending

Sorting Items – Descending

            Listview1.Sorting = SortOrder.Descending

Sorting Items – None (No Sorting at All)

            Listview1.Sorting = SortOrder.None

 

Shuffling, or Randomizing Items…

I will now provide source code to randomly sort all of the items in the listview control. I may see about a better solution to this but this code does work perfectly fine.

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

        Next

Sorting Items with a Column Click…

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

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

            Listview1.Sorting = SortOrder.Ascending

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

            Listview1.Sorting = SortOrder.None

        End If

    End Sub

_______________________________________

You see that it really is easy to do all of these tasks. I don’t exactly like the code I made on shuffling/randomizing the items so if I come up with something better I will update this article. I haven’t decided yet on what to do for the next Listview Control article. Hopefully it will prove to be useful… Feel Free to leave a comment if you have something in mind.  Have fun!

 

Jason

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


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

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

   

Removing Items…

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

 

Remove – All Items

        Listview1.Items.Clear()

   

 

Remove – Checkmarked Items Only

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

            Listview1.CheckedItems(0).Remove()

        Next

OR

        Do While Listview1.CheckedItems.Count > 0

            Listview1.CheckedItems(0).Remove()

        Loop

    

 

Remove – Selected Items Only

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

            Listview1.SelectedItems(0).Remove()

        Next

OR

        Do While Listview1.SelectedItems.Count > 0

            Listview1.SelectedItems(0).Remove()

        Loop

 

_______________________________________

 

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

Jason


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

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

 

Works for Both VB 5.0/VB6.0 and Visual BasicNET

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

 

_______________

'Visual Basic 5.0, 6.0 Declare

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

 

'Visual Basic.NET Declare

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

 

 

‘Remaining code for API Method for All VB’s below…
  
'For both VB and VB.NET. This variable is for receiving the path from the API call.

    Dim winDir As String

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

     winDir = Space$(255)

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

      GetWindowsDirectory winDir, Len(winDir)

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

      winDir = RTrim(winDir)

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

    MsgBox(winDir)

_____________

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

 

.NET based VB’s only below

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

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

….

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

….

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

_____________

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

         Jason

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

 

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

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

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

 
 
________________________

VB.NET

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

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

VB 6.0

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

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

________________________

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

VB.NET… 

    HideCaret(TextBox1.Handle.ToInt32)

    ShowCaret(TextBox1.Handle.ToInt32)
VB 6.0… 
    HideCaret Text1.hWnd

    ShowCaret Text1.hWnd
________________________
 
 
The codes above are set to Hide/Show the caret in a textbox control. If you want the cursor to never be shown in a textbox control, then simply put the HideCaret code in the Textbox_GotFocus() event. Like below… 
 
________________________
 
 
VB.NET 
 
Private Sub TextBox1_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus

HideCaret(TextBox1.Handle.ToInt32)

End Sub
 
VB 6.0 
Private Sub Text1_GotFocus()

    HideCaret(Text1.hWnd) 

End Sub 

________________________

 

 

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

 

                      Jason

Checking if Windows and/or your Program is 64-bit or 32-bit using VB.NET and Higher


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

 

Image of example application

 

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

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

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

        MsgBox(cpuID)

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

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

            MsgBox("It Is 64 Bit!")

        End If

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

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

            MsgBox("64 Bit!")

        Else

            MsgBox("32 Bit!")

        End If

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

I might add more to this little article in the future. Remember Visual Basic 2010 has a property you can check for the mode of the operating system. Simply check the: Environment.Is64BitOperatingSystem property. Thats all for now. Have fun!

 

Jason

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

 

Have you ever seen a program that can open a files destination/containing folder and also highlight/select the filename as well in the opened folder window? This little post will show you a simple way to do the same thing. Basically your using shell to access explorer.exe while passing certain command line arguments. All versions of Visual Basic and Visual Basic.NET can easily interface with with the explorer.exe process. VB.NET 2002, VB.NET 2003, VB.NET 2005, VB.NET 2008, and VB.NET 2010 will use exactly the same code. The classic VB’s like VB 5.0 and VB 6.0 will need an additional piece of code.

If your using Visual Basic Classic like VB 5.o or VB 6.0 then you need to add the API call based shell code below…

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

 

All thats left to do is call that shellexecute api function and pass the proper parameters and arguments. The same target process and arguments are used for VB.NET and pre.net vb’s. Here is the code to open the folder and select a filename using VB 5.0/6.0 and the ShellExecute api…

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

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

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

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

Jason

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

  I remember getting annoyed a long time ago when I would get that error message outlined in the title of this post. Although it happened along time ago I decided to write a brief post about it now anyways. You need to remember that this error message can occur in different scenerio’s and not just the way I got it.

I was trying to setup an example using VB 2005 that used my csRDTSC.DLL file to calculate the processor’s clockspeed and whenever I would call a function from the dll I would get the error message below…

   

‘BadImageFormatException was unhandled’

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

    

———-

   

Picture of the Bad Format Error Message

  

———-

  

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

I use as my main computer an Intel Core2 based processor/cpu which has 64 Bit support (x64 or AMD64 (Intel64 is a clone of AMD64), which is the code name) and I use Windows Vista 64 Bit. Thats obviously not a problem in itself. I made the csRDTSC.dll a long time ago, long before I upgraded to Vista 64. (BTW this error message will popup as well when running Windows7 64 Bit) But the C++ (C PlusPlus).Net .dll I made was based on Visual Studio.NET 2003 which will only compile 32 bit assemblies and was written using Windows XP Professional 32 Bit (x86). Of course thats not a problem either. (Microsoft says .NET older than 2005 should Not be used for programming on any variant of Vista). The problem was when the two came together. I use Visual Studio 2005 Standard Edition which can target both 32 Bit and 64 Bit cpu’s and by default the profile is – Target CPU: AnyCPU. Since my 64-bit CPU was running on a 64 bit Operating System, VS.NET would try to target using 64 Bit profiling instead of 32-Bit which the csRDTSC.dll was written as. And that turned out to be the reason I kept getting that incorrect format error message. The program was targeting 64 Bit mode but the .dll library I was linking to was 32 bit only. Obviously the compiler for 32 bit and 64 bit commands and what-not under the hood would have some differences. So apparently the compiler which was set to Target ‘AnyCPU’ was thinking in 64 Bit mode and didn’t understand how to handle that .dll library I made for 32 Bit.

   

———-

  

Picture of the Target CPU Compile Screen

———-

   

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

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

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

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

            

   Jason

Downloading Files with Advanced Features with VB.Net 2005 and Higher

The .NET Framework has always made it easy to download files. Dot.NET 2.0 added a new Async version of the DownloadFile feature. That basically means that if you use the DownloadFileAsync() sub it will download on a seperate thread instead of consuming your main application thread which makes your application appear frozen. If you didn’t want your apps thread tied up while downloading you would have to spawn a new thread when using the normal DownloadFile feature. So Microsoft made it alittle easier to download a file by adding the DownloadFileAsync method. By the way, this article and example works with Visual Basic 2008, and VB 2010 as well.

This is a simple article that will briefly highlight Downloading Files but the bulk of the code is only available in the VB.NET example program I made. There is way to much code to add to a simple 1 page article. I thought about making a 2 or 3 part article series but I still didn’t want to go through the process of adding the code and formatting it and such. Besides, seeing the code in action by downloading the example will make it easier to see how certain codes work and when to use them and when not to use them. But anyways, the example application will not only show how to download files using the DownloadFileAsync method, but also how to add advanced features and features that are NOT explicitly available in the DotNet framework.

Below are some of the major features of the download example application…

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

________________________________

This is the base DownloadFileAsync sub I used below…

 

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

 

As you can see its a very simple piece of code. The method is a part of the: System.Net.Webclient class. Webclient contains some very easy to use methods for uploading, downloading, and ect in your applications

Info: Since I can’t put all of the many lines of code in this article for the advanced features. Here is a link to my example download application. Continue reading the article for some more tidbits if your interested.

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

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

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

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

You can now get started performing the actual downloading.

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

Thats really all there is to it to get basic downloading support for your applications. What if you want download progress, size, speed, approximate time left till the download is finished and more? Well that is the reason I keep putting a link throughout this article to a full-featured download example application I made with Visual Basic 2005. The example program can be used in Visual Basic 2008 and Visual Basic 2010 as well. In case you don’t know by now I like Visual Basic.NET 2005 the best out of all Visual Studio .NET versions.I want to mention as well that the Webclient class has two very important events you can use for both the Download progress updates and an event for when the Download has finished.

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

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

All you have to do is AddHandler ‘s to each of those events to get downloading progress reports each time some data is received and when the file has completely finished downloading.

 A picture of what the example application looks like

________________________________

Looking at the screenshot above you can see just how many features that I include in the example. The application highlights everything I mentioned above and more. So if you want, or ever needed to download file from the internet then this Link will get you a example project with full source code just for you! Enjoy!

Jason

Detect when Removable USB/Volume Drive Devices are Added/Removed/Connected – VB.NET

Below is some code I saw on a vb message board along time ago but I can’t remember where. This source code uses mainly pure code without having to rely on a specific class or 3rd Party controls. The downside is that it is pretty complicated. But if I can get the formatting and stuff right you should be able to do a simple copy and paste. I made some minor code changes and tested the code and I have it throw a messagebox with the drive letter of the new usb device being attached. It does use application subclassing to intercept the messages and checks if any of them are a new removable volume or not. If it is then it will parse the drive letter of the newly attached device and throw a messagebox letting you know. Most usb devices such as flash drives (Thumb Drives or Pen Drive’s as they are also called), external hard drives, and such with a removable disk volume of some sort would be detected just fine. In all of my personal testing this code did it all! You can use this code with VB.NET, Visual Basic 2005, Visual Basic.NET 2008, and VB 2010 to check for the arrival of usb volume devices. You can also make some changes to make it work for VB 6.0 as well. IIRC Visual Basic 6.0 will need a addiional API call to do the subclassing portion.

_______________
 

 
These go in your declaration section of your program.
 

    '
    'Used to detected if any of the messages are any of these constants values.
    Private Const WM_DEVICECHANGE As Integer = &H219

    Private Const DBT_DEVICEARRIVAL As Integer = &H8000

    Private Const DBT_DEVICEREMOVECOMPLETE As Integer = &H8004

    Private Const DBT_DEVTYP_VOLUME As Integer = &H2  '
    '
    'Get the information about the detected volume.
    Private Structure DEV_BROADCAST_VOLUME

        Dim Dbcv_Size As Integer

        Dim Dbcv_Devicetype As Integer

        Dim Dbcv_Reserved As Integer

        Dim Dbcv_Unitmask As Integer

        Dim Dbcv_Flags As Short

    End Structure

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

    Protected Overrides Sub WndProc(ByRef M As System.Windows.Forms.Message)
        '
        'These are the required subclassing codes for detecting device based removal and arrival.
        '
        If M.Msg = WM_DEVICECHANGE Then

            Select Case M.WParam
                '
                'Check if a device was added. 
                Case DBT_DEVICEARRIVAL

                    Dim DevType As Integer = Runtime.InteropServices.Marshal.ReadInt32(M.LParam, 4)

                    If DevType = DBT_DEVTYP_VOLUME Then

                        Dim Vol As New DEV_BROADCAST_VOLUME

                        Vol = Runtime.InteropServices.Marshal.PtrToStructure(M.LParam, GetType(DEV_BROADCAST_VOLUME))

                        If Vol.Dbcv_Flags = 0 Then

                            For i As Integer = 0 To 20

                                If Math.Pow(2, i) = Vol.Dbcv_Unitmask Then

                                    Dim Usb As String = Chr(65 + i) + ":\"

                                    MsgBox("Looks like a USB device was plugged in!" & vbNewLine & vbNewLine & "The drive letter is: " & Usb.ToString)

                                    Exit For

                                End If


                            Next

                        End If

                    End If
                    '
                    'Check if the message was for the removal of a device. 
                Case DBT_DEVICEREMOVECOMPLETE

                    Dim DevType As Integer = Runtime.InteropServices.Marshal.ReadInt32(M.LParam, 4)

                    If DevType = DBT_DEVTYP_VOLUME Then

                        Dim Vol As New DEV_BROADCAST_VOLUME

                        Vol = Runtime.InteropServices.Marshal.PtrToStructure(M.LParam, GetType(DEV_BROADCAST_VOLUME))

                        If Vol.Dbcv_Flags = 0 Then

                            For i As Integer = 0 To 20

                                If Math.Pow(2, i) = Vol.Dbcv_Unitmask Then

                                    Dim Usb As String = Chr(65 + i) + ":\"

                                    MsgBox("Looks like a volume device was removed!" & vbNewLine & vbNewLine & "The drive letter is: " & Usb.ToString)

                                    Exit For

                                End If

                            Next

                        End If

                    End If

            End Select

        End If

        MyBase.WndProc(M)

    End Sub

 
_______________
 
Unfortunately the code is kinda complicated but it Does work. You may have to tinker with the code alittle since wordpress does a pretty bad job of formatting even though I insert the source code exactly the way it should be. I may add a example application eventually available for download. Hopefully this may help someone. Have Fun!          

Jason

How to Check if the Operating System is 32 Bit or 64 Bit using VB.NET – Updated: for VB 2010

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

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

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

 
____________________
 

For Visual Basic.NET 2010 Only…

 

 Environment.Is64BitOperatingSystem

 

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

 

MsgBox(Environment.Is64BitOperatingSystem)

 

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

 
_____________________
 

Visual Basic.NET Older than version 2010 continue on…

 

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

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

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

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

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

 
___________________
 

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

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

            Dim wmiClass As New System.Management.ManagementClass

            Dim wmiObject As New System.Management.ManagementObject

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

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

                Return getWMIInfo

            Next

        Catch exc As Exception

            Return exc.Message

        End Try

    End Function

 
___________________
 

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

 

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

 

 
___________________________________
 

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

Jason

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

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

Below are some highlights from the Microsoft HowDoI post…

—————-

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

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

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

Enjoy!

—————-

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

            Jason

Some Free Training and Tutorials from AppDev

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

———————-

Free ASP.NET and AJax Training – Download Page

Basic Overview…

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

———————-

Free Visual Studio 2008 Training – Download Page

Basic Overview…

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

———————-

Free Sharepoint Training – Download Page

Basic Overview…

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

———————-

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

            Jason

Free eBook, and other Free Resources and Source Codes

   

  Well its been awhile since i’ve updated the site. I am a Computer Tech so i’ve been busy building, upgrading, and fixing customers computers along with removing viruses. But anyways, there are somemore “stuff” i’ve come across that I thought would be worth posting. Some of these resources could be older and may have been posted on this site before. (Shouldn’t been to many though). Basically everything I post here is Free.

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

Clinic 6262: Introducing Windows Workflow Foundation using .Net Framework 3.5 & Visual Studio 2008

Introduction
This clinic will provide a start point for Enterprise Developers and Software Architects that are looking to Windows Workflow Foundation as a solution for enabling business processes within their solutions. Within the clinic you will learn about the functionality provided by the workflow engine, the overall architecture, and how to build workflow enabled applications.
Objectives

At the end of the course, students will be able to:

  • Describe the WF value proposition
  • - Describe Windows Workflow Foundation
  • - Describe Model driven benefits
  • - Describe how WF increases developer productivity
  • - Describe how WF allows increased collaboration between devs and business analysts
  • - Describe the benefits of OS integration
  • - Describe Scenarios for building WF
  • - Describe Microsoft products that will leverage WF
  • Describe how to build WF applications
  • - WF hosting environments
  • - Workflow Designer
  • - Workflow debugger
  • - XAML
  • Describe the WF architecture
  • - Workflow Runtime
  • - Workflows
  • - Activities
  • - Fault Handling
  • - Communication Activities
  • - Role Activities
  • - Custom Activities
  • New features in .NET 3.5
  • - Integration of workflow (WF) and services (WCF) as Workflow Enabled Services

Click Here to Check it Out!

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

Windows® API Code Pack for Microsoft® .NET Framework

The Windows® API Code Pack for Microsoft® .NET Framework provides a source code library that can be used to access some new Windows 7 features (and some existing features of older versions of Windows operating system) from managed code. These Windows features are not available to developers today in the .NET Framework.

The individual features supported in this version (v1.0) of the library are:

  • Windows 7 Taskbar Jump Lists, Icon Overlay, Progress Bar, Tabbed Thumbnails, and Thumbnail Toolbars.
  • Windows 7 Libraries, Known Folders, non-file system containers.
  • Windows Shell Search API support, a hierarchy of Shell Namespace entities, and Drag and Drop functionality for Shell Objects.
  • Explorer Browser Control.
  • Shell property system.
  • Windows Vista and Windows 7 Common File Dialogs, including custom controls.
  • Windows Vista and Windows 7 Task Dialogs.
  • Direct3D 11.0, Direct3D 10.1/10.0, DXGI 1.0/1.1, Direct2D 1.0, DirectWrite, Windows Imaging Component (WIC) APIs. (DirectWrite and WIC have partial support)
  • Sensor Platform APIs
  • Extended Linguistic Services APIs
  • Power Management APIs
  • Application Restart and Recovery APIs
  • Network List Manager APIs
  • Command Link control and System defined Shell icons.

 Click Here to Check it out!

—————

Additionally there are some Videos highlighting some of the code pack features.

Videos:
Two minute videos demonstrating some of the features in this release are now available:

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

 Understanding Microsoft Virtualization Solutions

 Info: This guide will teach you about the benefits of the latest virtualization technologies and how to plan, implement, and manage virtual infrastructure solutions. The technologies covered include: Windows Server 2008 Hyper-V, System Center Virtual Machine Manager 2008, Microsoft Application Virtualization 4.5, Microsoft Enterprise Desktop Virtualization, and Microsoft Virtual Desktop Infrastructure.

 If you want the entire eBook they have a link on the same page as the view Chapter 1.

 Click Here to Check it out!

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

 Collection 6261: Developing Rich Experiences using Microsoft .NET Framework 3.5 & Visual Studio 2008

  • Free: E-Learning Collection 6261: Developing Rich Experiences Using Microsoft .NET Framework 3.5 and Visual Studio 2008

    This series of three, two-hour clinics focuses on how to build solutions by using Windows Workflow Foundation, Windows Presentation Foundation, and Windows Communication Foundation with the Microsoft .NET Framework 3.5 and Visual Studio 2008.

  • Free chapters from Programming Microsoft LINQ, Programming Microsoft ASP.NET 3.5, and Introducing Microsoft Silverlight 2, Second Edition

  • More Info on the FREE e-Learning Collection…

    Overview
    This collection of 3 2-hour premium clinics teaches about the new capabilities provided by the .NET Framework 3.5. These clinics are for experienced Developers and Software Architects who are looking to adopt Microsoft’s next generation technology within their solutions.
     
    This offer includes the following:
    Clinic 6262: Introducing Windows Workflow Foundation using .Net Framework 3.5 & Visual Studio 2008
    Clinic 6263: Introducing Windows Presentation Foundation using .Net Framework 3.5 & Visual Studio 2008
    Clinic 6264: Introducing Windows Communication Foundation using .Net Framework 3.5 & Visual Studio 2008

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

    Thats all for now. Sorry about the structure and overall visual of this post. It looks kind of messy and confusing but I hope you can get the info you wanted. Take care!

            Jason

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

    This is a basic article on how to do various textbox manipulating that isn’t exposed in your normal VB or VB.NET textbox like Page Left or Scroll to the Edge (That I am aware of anyways).

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

    So in Part #1 of this article I will present some codes that will accomplish what is outlined below to a textbox control…

    Page Left

    Page Right

    Line Left

    Line Right

    Left Edge

    Right Edge

    _________________________________

    To accomplish these features I will use the tried and true Windows API. Specifically the SendMessage Function is used. Below is the declaration for VB Classic and VB.NET

    Visual Basic 6.0

    
        'Used to Send Messages to the 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
    
    

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

        'Used to Send Messages to the 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
    

    _________________________________
     

    Now for some Constants…

     

    Visual Basic 6.0…

    
        Private Const EM_SCROLL = &HB5
    
        Private Const SB_PAGEDOWN = 3
    
        Private Const SB_PAGEUP = 2
    
        Private Const SB_LINEUP = 0
    
        Private Const SB_LINEDOWN = 1
    
        Private Const SB_BOTTOM = 7
    
        Private Const SB_TOP = 6
    
    

     

    Visual Basic.NET through VB 2008 and VB 2010…

    
        Private Const EM_SCROLL As Int32 = &HB5
    
        Private Const SB_PAGEDOWN As Int32 = 3
    
        Private Const SB_PAGEUP As Int32 = 2
    
        Private Const SB_LINEUP As Int32 = 0
    
        Private Const SB_LINEDOWN As Int32 = 1
    
        Private Const SB_BOTTOM As Int32 = 7
    
        Private Const SB_TOP As Int32 = 6
    
    

     
    _________________________________

    Now all thats really needed is the textbox you want to send messages to and calling the sendmessage api with the right combination of contants to perform the intended function.

    _________________________________

    NOTE: If your using VB 5.0 or VB 6.0 then change some small things below…

    Change – txtControl.Handle.ToInt32   to   txtControl.hWnd

    Change – Unless your getting the SendMessage functions return value then remove the parentheses which are the ( and ) characters.

    Thats basically the only changes that are needed.

    _________________________________

    Page Left / Page Right

            'Move the position pageleft.
    
            SendMessage(txtControl.Handle.ToInt32, WM_HSCROLL, SB_PAGELEFT, 0)
    
            'Move the position pageright.
            SendMessage(txtControl.Handle.ToInt32, WM_HSCROLL, SB_PAGERIGHT, 0)
    

    Line Left / Line Right

            'Move the position left.
            SendMessage(txtControl.Handle.ToInt32, WM_HSCROLL, SB_LINELEFT, 0)
    
            'Move the position right.
            SendMessage(txtControl.Handle.ToInt32, WM_HSCROLL, SB_LINERIGHT, 0)
    

    Left Edge / Right Edge

            'Move the position to the left edge.
            SendMessage(txtControl.Handle.ToInt32, WM_HSCROLL, SB_LEFT, 0)
    
            'Move the position to the right edge.
            SendMessage(txtControl.Handle.ToInt32, WM_HSCROLL, SB_RIGHT, 0)
    

    _________________________________

    Thats basically all for Part #1. These 6 features do not have native VB or VB.NET codes and therefore the API’s are used. As you can see though its pretty simple to add..

    Part #2 will go over: Page Up/Page Down, Line Up/Line Down, and Top Edge/Bottom Edge.

    Till then, Have fun!

    Jason

    Next Page »