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

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



Next Page »