Category Archives: Controls/Objects

List of articles related to application controls, custom controls, or objects for all VB & .NET.

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…

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

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

    HideCaret(TextBox1.Handle.ToInt32)

    ShowCaret(TextBox1.Handle.ToInt32)

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…

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.


That’s all for this tip I guess. 🙂

Jason

Minor Revision: 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!

Jason

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!"
        MsgBox(myString)

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!

Jason

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: vbcodesource.com but you can put the url you want. But Do Not include the http:// portion of the url, it will cause the ping to fail. Now just click on the command buttons that has the code and you should see the status of the pings in the label controls…

Image of the final product :)


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

               Jason

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.Add(f.Name)

    .Items.Item(x).SubItems.Add(f.Extension)

    .Items.Item(x).SubItems.Add(f.DirectoryName)

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

    .Items.Item(x).SubItems.Add(f.Exists)

  Next

End With

Just a tip for those who may not know.

           Jason

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…


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 🙂

Jason

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!

Jason

Minor Revision: 2015