Category Archives: Controls/Objects

List of articles related to application controls, custom controls, or objects.

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

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

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

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

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

Sorting Items…

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

Sorting Items – Ascending

            Listview1.Sorting = SortOrder.Ascending

Sorting Items – Descending

            Listview1.Sorting = SortOrder.Descending

Sorting Items – None (No Sorting at All)

            Listview1.Sorting = SortOrder.None

Shuffling, or Randomizing Items…

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

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


Sorting Items with a Column Click

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

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

            Listview1.Sorting = SortOrder.Ascending

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

            Listview1.Sorting = SortOrder.None

        End If

    End Sub

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


Minor Revision: 2015

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

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

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…


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

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

VB 6.0

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

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

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




VB 6.0

    HideCaret Text1.hWnd

    ShowCaret Text1.hWnd

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

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


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


End Sub

VB 6.0

Private Sub Text1_GotFocus()


End Sub

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

That’s all for this tip I guess. 🙂


Minor Revision: 2015

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

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

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

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

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

‘BadImageFormatException was unhandled’

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

Picture of the Bad Format Error Message

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

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

Picture of the Target CPU Compile Screen

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

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

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

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


Revisited: 2015

Free eBook: Patterns & Practices Application Architecture Guide 2.0

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

A while back Microsoft made available a new eBook for free called: Patterns and Pratices Application Architecture Guide 2.0

The download is about 3 megs of info and in the .pdf format. This book is should be very useful and helpful for .NET developers. Below are some of the features and Chapters in the free book.


Part I, Fundamentals
Part II, Design
Part III, Layers
Part IV, Archetypes


  • Foreword by S. Somasegar
  • Foreword by Scott Guthrie


  • Introduction
  • Architecture and Design Solutions At a Glance
  • Fast Track


Part I, Fundamentals

  • Chapter 1 – Fundamentals of Application Architecture
  • Chapter 2 – .NET Platform Overview
  • Chapter 3 – Architecture and Design Guidelines


Part II, Design

  • Chapter 4 – Designing Your Architecture
  • Chapter 5 – Deployment Patterns
  • Chapter 6 – Architectural Styles
  • Chapter 7 – Quality Attributes
  • Chapter 8 – Communication Guidelines


Part III, Layers

  • Chapter 9 – Layers and Tiers
  • Chapter 10 – Presentation Layer Guidelines
  • Chapter 11 – Business Layer Guidelines
  • Chapter 12 – Data Access Layer Guidelines
  • Chapter 13 – Service Layer Guidelines


Part IV, Archetypes

  • Chapter 14 – Application Archetypes
  • Chapter 15 – Web Applications
  • Chapter 16 – Rich Internet Applications (RIA)
  • Chapter 17 – Rich Client Applications
  • Chapter 18 – Services
  • Chapter 19 – Mobile Applications
  • Chapter 20 – Office Business Applications (OBA)
  • Chapter 21 – SharePoint Line-Of-Business (LOB) Applications



  • Cheat Sheet – patterns & practices Pattern Catalog
  • Cheat Sheet – Presentation Technology Matrix
  • Cheat Sheet – Data Access Technology Matrix
  • Cheat Sheet – Workflow Technology Matrix
  • Cheat Sheet – Integration Technology Matrix

As you can see, this book can be very useful and helpful for those programming using the .NET framework. I recommend you download and check it out. Have fun!


More Microsoft “How Do I” Video Updates and Service Pack 1 for 2008

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

I just wanted to mention that Microsoft officially launched the RTM version Service Pack 1 for Visual Studio 2008 a couple weeks ago. It includes many fixes and some other features and improvements. WPF (Windows Presentation Foundation) performance has been greatly increased as well. Click Here to check out the Service Pack for VB 2008.

Also Microsoft has been adding new How Do I videos for Visual Basic 2008 the past couple of months it appears. Its definitely worth checking out. It looks like Microsoft added many newer videos working with Excel and Microsoft Office and services. Linq and data-based programming looks to be updated as well. Remember that MSDN has many 2005 based videos as well. Anyways, Click Here if you want to check out the full list of MSDN’s “How Do I” video series. Have Fun!


Textbox Scroll with Cursor to the Top or Bottom with VB and VB.NET

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

I originally made this post for VB 6.0, but I figured I would go ahead and add the .NET code here as well. The first codes is for VB 6.0 and the code after is for Visual Basic.NET , VB 2005/2008, VB 2010, and newer.

Visual Basic 6.0

This will scroll to the bottom of the textbox control.

Text1.SelStart = Len(Text1.Text)


The code below will put the cursor to the beginning of the textbox and scroll to its position.

'Goto the top/first character in the textbox control.
TextBox1.SelStart = 0

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

This will put the cursor position at the bottom and scroll the textbox to the end of its contents.

'Set the cursor to the end of the textbox.
Textbox1.SelectionStart = Textbox1.TextLength
'Scroll down to the cursor position.


The codes below will set the cursor and scroll the textbox to the top or beginning of its contents.

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

Minor Revision: 2015

Getting the Current Line Number in Textbox using VB.NET

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

There is unfortunately no so-called ‘built-in’ way to get the current line number in a Visual Basic.NET Textbox control. Microsoft added that support in Visual Basic 2005/2008/2010. But many still use the original .NET versions which do not have that feature in the textbox control.

What to do? Well, there is a somewhat easy way to add this feature by using the Windows API. The API to use is the SendMessage API call. Below is the declaration, constant value, and line# variable…

Getting the Current Line Number code

    'Unfortunately, .NET before 2005 doesn’t have a built-in feature to get the current
    'line. So I am using the SendMessage API to do it. You CAN do various extractions or
    'whatever to do it, but this is easier and more elegant in my opinion.
    'Used to Send Messages to the control and will be used with a request for the
    'current line number in the textbox control.
    Private Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal winHandle As Int32, _
        ByVal wMsg As Int32, ByVal wParam As Int32, ByVal lParam As Int32) As Int32
    'Constant found in the VB 6.0 API Viewer App IT will be passed to the SendMessage
    'API to tell the control to give the current Line # from the textbox character position.
    Public Const EM_LINEFROMCHAR = &HC9
    'Will be used to contain the current line #.
    Dim lineNum As Int32

You can put the codes below in the textbox_Click, textbox_Keydown, textbox_TextChange event you want to take place or a button control  to get the line# results or whatever. In other words, put the code for where/when you want the current line results.

I put these codes in the Textbox_TextChanges event and used a label control to display the current line number. Its also worth nothing that Windows reports line # starting at “0”. So if the API returns a “0”, you can Add (+) one to the value which will then show the line# as 1. Another example is if the Windows API returns a 1, but in reality the current line is the second, then as before simple add (+) a One(1) to the value which will then be line #2.

        'Call the API to get the Line # from the current char. Txt is your textbox control.
        lineNum = SendMessage(txt.Handle.ToInt32, EM_LINEFROMCHAR, -1, 0)
        'Windows sees the first line in a edit box as line 0. So just add a value of 1 to the
        'result if you want the first line to be line #1.
        lblCurrent.Text = "Current Line: #" & (lineNum + 1).ToString
        'Check for line count first to keep a possible error from happening if the textbox has
        If txt.Lines.Length > 0 Then
            'Get the text at the current line position.
            txtLineText.Text = txt.Lines.GetValue(lineNum)

        End If

Thats all there is to it! When you run your project and type your characters or make a new line or whatever in the textbox, the label control should show the number that the caret or cursor is currently at. If you want the Line # code to be updated when the mouse clicks on a different line or position, simply put the code above in the textbox_Click event. Have Fun!


Revisited: 2015

Auto Complete Support in Textbox and Combobox Controls using VB 6.0 and VB.NET

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

Autocomplete is a very useful feature that Microsoft added with the release of Internet Explorer 5.0 and therefore Internet Explorer 5.0 or higher needs to be installed on the target computer. Adding autocomplete to your applications can be a real benefit to the user and is a easy feature to implement.

Note: Visual Basic 2005 and Visual Basic 2008 already has Autocomplete capabilities in the Textbox and Combobox controls by default.

There are a few different locations you can get the autocomplete data from…

  • File System
  • History List
  • URLs Recently Used
  • ALL URLs
  • ALL System Sources

There are likewise a few different options available to set the way you want AutoComplete to react.

  • Append
  • Suggest
  • Append & Suggest

Visual Basic.NET

    'The API call that enables the autoComplete feature to your combo or textbox controls.
    Private Declare Sub SHAutoComplete Lib "shlwapi.dll" (ByVal controlHandle As Int32, ByVal _
        completeFlags As Int32)

Visual Basic 6.0

    'The API call that enables the autoComplete feature to your combo or textbox controls.
    Private Declare Sub SHAutoComplete Lib "shlwapi.dll" (ByVal controlHandle As Long, ByVal _
        completeFlags As Long)

The SHAutoComplete API Sub is easy to use. The first parameter is the Handle to the Edit (Combobox/Textbox) control you want to enable Auto Complete too. The second Parameter is how you want your Autocomplete to react and display.


    'Various Flags you can set to be the source.
    Private Const Defaults = &H0

    Private Const Filesystem = &H1

    Private Const HistoryList = &H2

    Private Const URLRecentlyUsedList = &H4

    Private Const AllURLs = (HistoryList Or URLRecentlyUsedList)

    Private Const AllSystemsSources = AllURLs Or FileSystem

The flags below are used to specify how you want your autocomplete feature to react.

    'Flags you can use to specify how your want autocomplete to react.
    Private Const append = &H40000000 Or &H20000000

    Private Const suggest = &H10000000 Or &H80000000

    Private Const suggestAppend = &H40000000 Or &H10000000

Now that the API based codes are out of the way, you can setup the edit based controls (Like Textbox and Combobox) to have Autocomplete capabilities. Below is a simple example of adding autocomplete to a textbox control that I named txt.

        'Set autocomplete to the textbox using the system defaults.
        SHAutoComplete(txt.hWnd, Defaults)

        'You can also specify how it will react and what it will display.
        SHAutoComplete(txt.hWnd, suggest Or AllURLs)

If your using .NET, just change txt.hWnd to txt.Handle.ToInt32.

Unfortunately adding this feature to a Combobox isn’t as straight forward. Thats because when you use the Handle/Hwnd Property for the Combobox it returns the Main Window Portion of the control and NOT the Edit Window portion. There are a couple ways to get around this though. One way it to use the GetComboBoxInfo API or to use the FindWindowEx API call. I chose to go ahead and use the FindWindowEx API.

Visual Basic.NET

    'API Function used to get the Edit window of a combobox control.
    Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As  _
        Int32, ByVal hwndChildAfter As Int32, ByVal lpszClass As String, ByVal lpszWindow As String) As Int32

Visual Basic 6.0

    'API Function used to get the Edit window of a combobox control.
    Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal handle As _
        Long, ByVal hwndChildAfter As Long, ByVal lpszClass As String, ByVal lpszWindow As String) As Long

Now you just need to use the FindWindowEx Function using the 1st and 3rd parameter. And once you call the FindWindow function, simply pass its return value to the SHAutoComplete Method.

        'Simply change this variable type to a Integer if your using VB.NET.
        Dim cmbHandle As Long

        'Retrieve the handle to the ‘Edit’ Window of the combobox. I named my Combobox control cmb.
        cmbHandle = FindWindowEx(cmb.hWnd, 0, "Edit", vbNullString)

        'Activate Autocomplete to the combobox edit window.
        SHAutoComplete(cmb.hWnd, Defaults)

Tip: Here is how you can specify exactly how to react and display….

        'You can also specify how it will react and what it will display.
        SHAutoComplete(cmb.hWnd, suggest Or AllURLs)

Again, change cmb.hWnd to cmb.Handle.ToInt32 if your using Visual Basic.NET.

Thats all there is to it! Depending on your application, you or your apps user will really appreciate you putting that feature in your program. Well, I guess there is nothing more to add. Have fun!


Make Custom or Abnormal Shaped Forms in .NET

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

There may be a time when you get tired of the same old rectangle based form. You may even want to make the form a shape of a circle or work with skins. You needed to use Windows APIs to do it in 6.0. In VB.NET, Visual Basic 2008, VB 2010, and newer this is done pretty easily.

There are a few different ways to set your forms shape. I will use the GraphicsPath class in this article.

Variables/Objects to Make

  • new – GraphicPath
  • new – Region
  • new – StringFormat

    'Used to specify the Shapes, Text, and what-not.
    Dim p As Drawing2D.GraphicsPath = New Drawing2D.GraphicsPath

    'The region to pass to the form once its setup.
    Dim reg As Region

    'Used to specify the way to format the strings.
    Dim sf As New StringFormat

Once that is taken care of, specify what and how to display your forms region. In this example I am going to make the form a Ellipse shape and with a Text/String region as well.

        'Add a shape to display the region as.
        p.AddEllipse(0, 0, 100, 200) '

        'Add some text to display as well.
        p.AddString("Visual Basic for FREE!", FontFamily.Families.GetValue(1), FontStyle.Regular, 15, New Point(100, 100), StringFormat.GenericDefault)

        'Simply create a new Region object with the information in the Graphics Path.
        reg = New Region(p)

        'And the last is to set the newly created region for the form to display.
        Me.Region = reg

Results of the code in this article

That all there is to it. There are pretty much unlimited shapes you could make your form display as. This example works with Visual Basic.NET, Visual Basic 2008. VB 2010. and newer. Anyways, Have Fun!


Revised: 2015

How to do Multi-Line Messageboxes and Inputboxes in VB 6.0 and in VB.NET

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

How to do Multiple Lined Messages (Input and Messagebox) is a very common question. Unfortunately the Message Functions do not have a native multi-lined option. But there is a simple workaround to create messages on different/separate lines. It is a little constant called: vbNewLine which is evidentially a brother to the vbCrLf constant.

Public Const vbNewLine As String = vbCrLf

Public Const vbCrLf As String = vbCrLf

These constants are basically the same as combining Chr(13) and Chr(10) characters which maps to the Carriage Return – Line Feed. Using the constants is very simple. Just add the constant outside the string that you want to start a new line at. Below is basic examples of using them…

        'Create a new string to display.
        Dim myString As String

        myString = "I want a Multi-Lined Message!"

Now that there is a string to use, simply add the vbNewline constant as so…

        myString = "I want a Multi-Lined Message!" & vbNewLine & vbNewLine & "This message is under the first!"

The “myString” variable should now display as a multiline string.

The multilined messagebox.

That’s all you have to do! The vbNewline Constant (vbCrlf also) is all you need to do to make most multi-lined messages. This is a simply fix and should work just fine for most messagebox/inputbox messages and such.

Remember that these constants are available in ALL versions of Visual Basic. VB 6.0 through to VB.NET 2008, VB.NET 2010, and VB 2013. Have Fun!


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

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

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

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

VB 6.0 Project with Compiled .NET Wrapper

VB 2005 Project with Compiled .NET Wrapper

Getting Started…

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

Adding the ComClass view

Add these Import Statements right above your Class.

Imports System.Net.NetworkInformation

Imports System.Windows.Forms

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

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

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

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

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

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

        Dim p As New Ping

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

        Return CInt(reply.RoundtripTime)

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

A reference view in VB 6.0

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

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

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

    Private Sub cmdPing_Click()

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

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

        End If

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

    End Sub

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

    Private Sub cmdSendTime_Click()

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

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

        End If

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

    End Sub

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

Image of the final product :)

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


Visual Studio 2005 IDE Enhancement Extensions

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

These resources are oldies but goodies. The enhancements are for version 2005 and includes a few different tools/resources or “Visual Studio Extensions”. Below is a overview as outlined by Microsoft…


Visual Studio 2005 IDE Enhancements are a set of Visual Studio extensions that are designed to make you more productive. These enhancements are directly integrated into the Visual Studio IDE. This set of enhancements includes Source Code Outliner, Visual C++ Code Snippets, Indexed Find, Super Diff and Event Toaster tools. All these tools except the IDE Event Toaster can be invoked from Visual Studio’s View.OtherWindows menu group. The Event Toaster tool can be configured from the Tools Options dialog under the PowerToys node. The Visual C++ Code Snippets can be invoked on any C++ source file. Previously, these enhancements were only available via the Visual Studio 2005 SDK. This installation does not require Visual Studio 2005 SDK.

Source Code Outliner : The Source Outliner tool is a Visual Studio extension that provides a tree view of your source code’s types and members and lets you quickly navigate to them inside the editor.

Visual C++ Code Snippets:The Visual C++ Code Snippets tool lets you insert snippets in your code by using a pop-up menu that contains programming keywords. VB.NET and C# languages have this functionality in Visual Studio 2005.

Indexed Find : The Indexed Find tool is a Visual Studio extension that uses the Microsoft Indexing Service to provide improved Search capabilities to the integrated development environment (IDE). It sends the results of a search to the Output Window.

Super Diff Utility: The Super Diff Find tool is a Visual Studio extension that compares text files. It uses color coding and graphics to show the difference between the files in deleted text (red), changed text (blue), inserted text (green).

Event Toaster Utility: The Event Toaster tool is a Visual Studio extension that notifies users about specific events within the Visual Studio IDE.

If you are interested in building your own Visual Studio extensions, you can download the Visual Studio 2005 SDK from here to get started.

So if you want these cool Extensions, just click this link to head over to the Microsoft Download page.


How to Display Text in the System Tray/Notify Icon in VB.NET and Higher

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

You’ve probably seen some applications that are able to display what looks like text in the notify icon system tray. You may have noticed that the NotifyIcon control we use in VB.NET has no feature for displaying actual text in the tray So, how could you show text in the icon tray like other applications do? A simple little trick will display your icon as text.

More Info…

You actually have to make a bitmap in memory, draw the text you want to display, and use that bitmap you made as the icon to show in the system tray or notify area as some call it. This article has full sample code to accomplish this using Visual Basic.NET, Visual Basic 2008, VB 2010, and Visual Basic 2013. You can also download an example for doing this by clicking here.

Unfortunately there is only about 16×16 pixels of space for your icon text. So it will definitely limit the amount of text you can show in each spot. You should experiment with different Font Types and Font Sizes to get the best results. I also recommend you set the TextRenderingHint property to a higher quality setting like AntiAliasing which could make the text look much better compared to the default rendering hint. Also try to fine tune the position of the text drawn on your Icon to make full use of the icon area.

Getting Started…

The first thing you want to do once you open up your project is add a NotifyIcon component to your project from the Toolbox. I named mine “notifyText”. You can also add a context menu to be used during a Right Mouse Click. Go to the Notify Icon Properties and under the ContextMenu option select the context menu if you added one. If you want, under the ‘Text’ property you can set the Tooltip Text for when the Mouse is hovering over the Notify Icon in the System Tray. There are also some events for the Notify Icon if you want to make use of them like _MouseDown, _DoubleClick, etc.

Visual Basic.NET, Visual Basic 2008, VB 2010, and Higher Source Code…

The first code is a “DestroyIcon” API Function I use to completely destroy/remove the icon from existance when i’m done with it. IF you do get a generic gdi+ error (or it may just say a Generic Error has Occured? I don’t remember), then try using this API call to kill the Icon you created in memory. I made an app that will display and update the cpu clockspeed/usage in the tray update every second or so and that Generic Error would popup every once in awhile and not really say much about it except it had something to do with something in the icon code. This function is good to use anyways to release the resources used by the icon.

    'I'm using this in the createTextIcon sub to releases all of the resources that the icon/icons would have used.
    Public Declare Function DestroyIcon Lib "user32.dll" (ByVal hIcon As Int32) As Int32

Remember to optimize your text icon as much as you can so you can take full advantage of the limited space you have available for clarity. Set the “System.Drawing.Text.TextRenderingHint” to “System.Drawing.Text.TextRenderingHint.AntiAlias” to get smoother and easier to read text. You should setup the font and X/Y coordinates to make full use of the small space. And of course select a brush color that the user would be able to see well.

The code here is the declaration based code for variables and such…

    'You should fine tune the font you want to use so the user can see the text you want them to see.
    'Certain Fonts will obviously display your text better than other fonts might.
    Dim fontToUse As Font = New Font("Microsoft Sans Serif", 8, FontStyle.Regular, GraphicsUnit.Pixel)

    'A basic brush with a Dark Blue Color. This should show up pretty well in the icon tray if the user uses the default tray color.
    Dim brushToUse As Brush = New SolidBrush(Color.DarkBlue)

    'A bitmap used to setup how the icon will display.
    Dim bitmapText As Bitmap = New Bitmap(16, 16)

    'A simply Grahics object to draw the text to a bitmap.
    Dim g As Graphics = Drawing.Graphics.FromImage(bitmapText)

    'Will be used to get the Handle to the bitmap Icon.
    Dim hIcon As IntPtr

The code below will draw the text onto the bitmap image and set the notify icon to display it by using its handle.

    'This code was actually taken from my CPUMonLite Application which displays the processors clockspeed in
    'the system tray. But the clockspeed code is removed
    Sub createTextIcon()


            'Clear any previous ‘stuff’ instead of creating a new bitmap.

            'Setup the text, font, brush, and position for the system tray icon. For the font type and
            'size I used, a good position for the X coordinate is a -1 or -2. And the Y coordinate seems
            'to work well at a 5.
            'You specify the actual text you want to be displayed in the draw string parameter that you
            'want to display in the notify area of the system tray. You will only be able to display a
            'few characters, depending on the font, size of the font, and the coordinates you used.
            g.DrawString("Text!", fontToUse, brushToUse, -2, 5)

            'Get a handle to the bitmap as a Icon.
            hIcon = (bitmapText.GetHicon)

            'Display that new usage value image in the system tray.
            notifyText.Icon = Drawing.Icon.FromHandle(hIcon)

            'Added this to try and get away from a rare Generic Error from the code above. Using this API Function seems to have stopped that error from happening.

        Catch exc As Exception

            MessageBox.Show(exc.InnerException.ToString, "Somethings not right?", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

    End Sub


The code from this article in use!


Now all you have to do is call that Sub above each time you want the text to change/update in the System Tray! Hopefully I made some sense in this article and you were able to follow ok. Have fun!


Minor Revision: 2014

Import Namespaces to save Time and Write Less code

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

Importing Namespaces can save some time/typing when accessing its methods/properties/objects since you won’t have to refer to the actual namespace when using one of its members.

Example Below…

Without Importing

'Without Importing the Namespace...


With Importing

'With the Namespace Imported...


The Importing example above saved time and code writing since you won’t have to include the System.IO. namespace every time you access one of its members. There are a couple ways you can import your Namespace. One way is adding the Imports statement with the Namespace just above where your Class begins and works for all .NET versions. Example…

Imports System.IO

Public Class frmMain

Inherits System.Windows.Forms.Form

'your code....

End Class

Another way is from the Projects Property page. To get to it simply go to the Project – Menu and click on your Projects – Properties Item which is usually the last item in the list.

Visual Basic.NET 2002/2003

Under “Common Properties” click on the “Imports” option. You will see a Namespace Textbox and a List of the currently Imported Namespaces. Simply type in the Namespace you want to add and click “Add Import”. Your Namespace will then be in the list and it is now “Imported” just as if you used the actual Imports statement.

Imports view for VB.NET.

Visual Basic 2005, Visual Basic 2008, and newer

For VB 2005 and VB 2008 adding Imports is under your Projects Properties page just like VB.NET 02/03. But it is under the “References” Tab. You will then see a list of References to the project and below that you will see the Imported Namespaces. Unlike VB.NET 02/03, there is actually a list of the common available Imports you can select. Just Check the Namespace you want to import and thats it. You can then use all of the Namespaces members and not have to include the namespace path which will save time and writing.

The VB 05/08 Imports view.

That’s all there is to it. Have Fun!


Use With/EndWith to Save Time and Typing in VB & VB.NET

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

This simple tip is just to show how you can do less typing and save time using the ‘With’ statement. This statement is nothing new as it has been around since the VB Classic (6.0) days. I usually do not remember to use this statement when I could benefit from it. So I wanted to write this post to simply remind those who may have forgotten about it or just don’t think about it when it could save time and do less typing. It didn’t occur to me until I had to refer to a Listview control many times to add information. It then came to me and by using this statement it saved me some time. IF you have to refer to a control or whatever and set alot of its properties or methods, then “With/EndWith” should be a welcome time saver. Below is a example of using he ‘With’ statement…

'Use a WITH statement to save some typing and time since you won't have keep referring
'to the object when you are setting its propertys and functions and what-not. LV is
'a Listview control.

With lv

  For x AsInteger = 0 To length - 1 

    f = New IO.FileInfo(s.GetValue(x))




    .Items.Item(x).SubItems.Add(f.Length / 1000 & " KBs") 



End With

Just a tip for those who may not know.


FREE eBook – Upgrading Microsoft Visual Basic 6.0 to Microsoft Visual Basic .NET

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

This is another resource that how been around for awhile but is still plenty useful and helpful. Especially if your a Visual Basic 5.0/6.0  developer making the move to Visual Basic.NET. It is pretty large and covers a wide range of areas taking up TwentyOne(21x) Chapters. It goes over The differences between VB Classic and .NET to Resolving Upgrade Issues and Preparing your Applications for the Upgrade. Below is a small excerpt…


Upgrading Microsoft Visual Basic 6.0 to Microsoft Visual Basic .NET is the complete technical guide to upgrading Visual Basic 6 applications to Visual Basic .NET, covering all upgrade topics from APIs to ZOrders. It shows how to fix upgrade issues with forms, language, data access, and COM+ Services, and how to upgrade applications with XML Web services, ADO.NET, and .NET remoting. It also provides big-picture architectural advice, a reference of function and object model changes, hundreds of before-and-after code samples, and a CD packed with useful examples.

If you are interested in this resource, then click this link to check it out. Try this link as well. Have fun 🙂


Two New Features in Visual Basic 2008 and Express

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

Old and possible Obsolete Article

Visual Basic 2008 does have quite a few features over 05. A lot of these features are added to the 3.0-3.5 version of the Dot Net Framework. VB 08 includes design support for WPF (Windows Presentation Foundation, WWF (Windows Workflow Foundation; It used to be called WinFX), ), WCF(Windows Communication Foundation), etc. You can click here to get a overview of WWF. IF you want to get started with WPF, you can click here. IF interested in WCF, then check it out here.

Another big feature for VB 08 is LINQ(Language Integrated Query). LINQ adds query capabilities for collections, SQL databases, ADO.NET Datasets, and XML documents. IF you do want to get started with LINQ, you can go to this MSDN Link and get going.

But I was more interested in taking a look at the somewhat ‘lesser’ hyped features for VB 9.0. I will try to put down some of the stuff I read at msdn. Its quite possible I may not add anything more useful than you already know 🙂 And I hope I do not explain something with the wrong answer 🙂 Feel free to leave a comment to let me know…

Local Type Inference

This little feature now makes it possible that you do not have to specify the actual type for local variables. It will set the type on its own depending on what value it ends up containing…

'This is the normal, traditional way of declaring variables...

Dim testWithType As Integer = 100


Dim testWithType As Integer

testWithType = 100

Now setup a new variable with Local Type Inference…

Dim testNoType

testNoType = 100


Dim testNoType = 100

'You can check which type was assigned to the variable with the code below if you want...


Based on the value of 100 that was set to it, it ends up being a Integer and the Msgbox message should display the type as ‘Integer’. P

Pretty nifty feature? The less code you have to write the better?

Object Initializers

Object initializers enable you to initialize a complex object and specify its properties by using one expression. In other words, when you declare a new object, you can use the With statement after the object you are wanting and add brackets after the With statement {  }. Inside the brackets you can automatically set properties related to that object.

Say you wanted to create a new Form, and want the .Backcolor a certain color and the MaximizeBox property set to False. You can automatically set these properties inside the Initializer Brackets. A example code for performing this is below…

See the Object Initializers in use…

Dim frm As New Form With {
    .BackColor = Color.Aqua,
    .MaximizeBox = False,
    .ForeColor = Color.Blue,
    .Owner = Me}

Pretty spiffy huh?

Well, those are two features I will use and wanted to outline them here. I may add another article with some of the other new features like Anonymous Types, Extension Methods, ect… But I do not feel like it now. Anyways, hope this small article was worth the read…


How to Easily add a Preconfigured SplashScreen with Visual Basic 08, VB 2010, and newer

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

This little tip is only to show how to very simply add a default Preconfigured Splashscreen to your project, not really anything beyond that 🙂 This feature is available in VB 2005, Visual Basic.NET 2008, Visual Basic 2010, and higher. The first thing you want to do is goto the “Project” menu and click on.. “Add New Item”. IT will then display a window with the available objects you can add to your project. Find and Click on the “SplashScreen” object. IT will then add the object to your project. Now all you have to do is simply go back to the “Project” menu and click on your projects “Properties” selection. On the “Application” tab your will see a option for “Splash Screen”. In that combobox simply select the new Splash Screen form you added earlier. Now your project will show that splash form when your program is loading. The default splashscreen is probably not how you want it to be for your application, so you can design the splashscreen form however you like. There is a feature for your Splashscreen that you might want to use. Its called: MinimumSplashScreenDisplayTime. As the name suggests, it will set the minimum time that your splashscreen will be visible via a milli-seconds value. IF you set it to 5000(ms), then your splashscreen will stay opened for 5 seconds before your main application form is loaded. Edit: Click here to see how to add the code  in Application Events. Example:

My.Application.MinimumSplashScreenDisplayTime = 1000

Well, that’s all there is to it to add a preconfigured default Splash screen form to your projects. Remember this tip will ONLY work with Visual Basic 2005 and Visual Basic 2008. Or as some like to call Visual Basic 8 and Visual Basic 9. Have fun 🙂


Revised: 2015

How to Move or Drag a Form without a Titlebar using VB 6.0 and VB.NET

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

There is more than one way to move a form without a title bar. For instance using API’s and Subclassing. But you can also use regular code and simply track the position of the mouse at certain events and can thus move the form without Subclassing. The regular code way is what I actually prefer and will show in this article.

The basics of the source code is keeping track of the mouse location when the form’s  _MouseDown event is fired and in the form’s _MouseMove event while the left Mouse-Button is still active. The first sets of codes will be for Visual Basic .NET including Visual Basic 2005/08 and Newer. Visual Basic 6.0 codes are further below.

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

Put these in your programs Declaration area.

    'These should go into your projects Declare area.
    Dim moveStartX As Integer

    Dim moveStartY As Integer

    Dim moveEndX As Integer

    Dim moveEndY As Integer

The variables above will hold the mouse starting position for when the left button is pressed and the ending position for when the mouse is moved.

Next, you want to go to your Forms_MouseDown() event…

    Private Sub frmMain_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) _
      Handles Me.MouseDown
        'Keep track of the mouse starting position when the mouse button is pressed.
        moveStartX = e.X

        moveStartY = e.Y

    End Sub

The final set of codes needs to go into your Forms_MouseMove() event…

    Private Sub frmMain_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) _
      Handles Me.MouseMove
        'Calculate the mouse positions in relation to its starting position.
        moveEndX = e.X - moveStartX

        moveEndY = e.Y - moveStartY
        'Make sure the Left Mouse Button is pressed and then move the form to its new location.
        If e.Button = Windows.Forms.MouseButtons.Left Then

            Me.Location = New Point(moveEndX + Me.Location.X, moveEndY + Me.Location.Y)

        End If

    End Sub

So, all of the VB.NET codes above will move your Form pretty much the same way as if you had moved the form with the Titlebar..

Visual Basic 6.0

You can put these in the Declaration area.

    'Declare the variables that will hold the mouse locations. This is almost exactly the same
    'as .net but the variables types needs to be changed from Integer to Long since the
    'Visual Basic 5.0/6.0 32Bit variable is Long and DotNets is Integer.
    Dim moveStartX As Long

    Dim moveStartY As Long

    Dim moveEndX As Long

    Dim moveEndY As Long

These go in the Forms_MouseDown event.

        'You want to put these codes in your Forms_MouseDown event. This will keep track of
        'where the mouse is positioned when the button is clicked.
        moveStartX = X

        moveStartY = Y

Then these go in the Forms_MouseMove Event.

        'Put the codes below in your Forms_MouseMove event…
        'Calculate the mouse position from its starting point to its current location.
        moveEndX = X - moveStartX

        moveEndY = Y - moveStartY

        If Button = 1 Then

            Me.Left = Me.Left + moveEndX

            Me.Top = Me.Top + moveEndY

        End If

That is all you have to do to get your form moveable if you have a non-title based form design. Have fun!


Minor Revision: 2015

Microsoft Visual Basic 2005 Power Packs 2.0

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

Line and Shape controls, PrintForm component, and Printer Compatibility Library all rolled into one download.

Click here to go to the Microsoft page