Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
XML RSS Feed
Tips & Tricks
These are brief tips and tricks that can make Visual Basic programming easier.
New Control Usage Numerical Stuff
Starting & Stopping I/O Bug Alerts
Software Engineering Printing System Issues
Graphics Coding Techniques Other Programs
Databases Misc Forms
Web

Starting & Stopping

Create URL Shortcuts
Ariel Canievsky.
Suppose that you only work with Visual Basic, and you want your computer to be most faster in start up and close up. Well, I have the solution:

Go to the System.ini file and modify the Shell line. If you want to run only VB, you can set

    Shell=3DC:\...\VB5.exe
And, if you close the window, you'll close the whole OS.
Open .VBS Files Safely
Yet another stupid email virus is making the rounds. It comes as an attachment named Something.jpg.vbs. You are supposed to see the ".jpg" part and assume it's a picture, not noticing the ".vbs" part which means it's actually a Visual Basic Script virus that, as usual, emails itself to everyone in your Outlook address book.

Here's a way to prevent yourself from accidentally running this kind of virus.

Create a text file using Notepad and rename it to "test.vbs". In Windows Explorer, Shift-Right Click on the file and select the "Open With" command.

Pick Notepad or Wordpad to open the file. Neither Notepad nor Wordpad can execute a Visual Basic Script. Check the "Always use this program to open this type of file" box and click OK.

Now if you receive a virus like this one and you accidentally try to open it, the system will use Notepad or Wordpad to show you the file instead of executing it and trashing your system.


Create URL Shortcuts
Henry Collingridge.
Try this:
  1. Open IE and go to the site you want to be your favourite.
  2. Right-click and drag the little explorer document icon from the address window over the start button (still dragging at this stage). Wait a second and the start menu appears.
  3. Now you can drag the icon to wherever you want it on the menu. When you let go, you get a shortcut menu offering to 'Create a Shortcut Here'.
Try using right-click/drag in other situations - e.g. dragging cells in Excel, files in explorer, etc.
Multiple INI Files
Trevor Finch has this startup directory tip:

It can also be useful at runtime to have the INI file in the 'StartIn' directory instead of 'App.Directory' or 'C:\WINDOWS'

This means that a user could have different configuration settings, data files, etc depending on what is the StartIn directory.

If Word did this you would have at the bottom of the file menu a list of 'recent files' that would be different depending on which icon was used to start Word - they would be saved in an INI file in each sub-directory.


Visual Basic Start Directory
I haven't been able to figure out how to make Visual Basic start itself in a particular directory, but Bernie Hanson and Scott Carpenter came up with this trick.

Create a shortcut to start Visual Basic. Right click on it and select properties. Click on the Shortcut tab and enter the directory where you want Visual Basic to start in the "Start in" field.

Now when you use the icon to start Visual Basic, you won't have to navigate your way out of some silly place like C:\Program Files\Microsoft Visual Studio\Vb98. You could even make more than one shortcut to start in different directories for different projects.


Start Visual Basic With a Project Loaded
Bruce Deam adds this to the previous tip:

You can take this a step further and (using the right mouse button) drag the .prj file into either the start menu or the taskbar. Create a link when prompted as making a copy will start in an equally undesirable place. Then you can start VB with the desired project already loaded!


Make an Autorun CD-ROM
To make the system automatically run a program when a CD is inserted, put a file on the CD named "Autorun.inf" and make it look like this:
    [autorun]
    OPEN=SETUP.EXE /AUTORUN
Replace SETUP.EXE with the program on the CD that you want to run.

Note that the user can disable the autorun feature on his PC.

[The setup.exe created by VB 6's Package and Deployment Wizard doesn't seem to like the /AUTORUN flag so omit it. Rod]

Click here for information on this at Microsoft's Web site.


You can also add the line:
    ICON=icon_file
after the previous lines to display a particular icon.

Thanks to Brady Doll.


Robert Heinig has this to add:

Here's what I know in steno:

  1. Sections. Use one [autorun] section for intel. If you want to support alpha etc. use additional [autorun.alpha], [autorun.mips] etc.
  2. Standard.
        Open=<relative path>
        Icon=<relative path> [, Icon index]
        Defaulticon=<root path> [, Icon index]
    
    Yes, you can address specific icons in resources with their index, the first icon is index 0.
  3. Context Menu.
        shell\<verb> = <caption of menu entry>
        shell\<verb>\command = <path to execute for this verb>
    
    Use one or more of these for additional context menu entries for the drive root. I usually have readme and setup here (because autorun does not directly launch the setup).
        shell = <verb>
    Use this to change the default action from autorun to one of your verbs.
  4. Refer to Q136214 to test this with floppies, ZIP drives or network mappings.

For more options, go to click here.
Display Program Version
(By Bill Mosca)
Here's how to get the program version to show in a Form's Caption. In the Sub Form_Load() add this code:
    Me.Caption = Me.Caption & _
        App.Major & "." & _
        App.Minor & "." & _
        App.Revision

To set the version numbers, open the Project menu, select the Properties command, and click on the Make tab.

You can use a similar technique to display the version number in splash screens and About dialogs.


Put Notepad in the SendTo popup
(By Ted Fattaleh)
Its always pain to open Notepad and browse to open and edit a .vbp file.

Fix: Put a Notepad shortcut in the Windows\Send To folder. Any time you want to open a .vbp, .swt, .iwz, .ini, .sys etc with Notepad, right click file and select Send To\Notepad from Context menu.


Controlling Programs
Kenneth Ives has some advice on controlling an application:
  1. Always start your application from a BAS module named "Sub Main()".
  2. When shutting down, use a BAS subroutine (i.e. StopApplication()). In this routine, add this code:
        Dim frm as Form
    
        ' Loop thru the forms collection and
        ' unload all forms from memory
        For Each frm In Forms
              frm.Hide            ' hide the form
              Unload frm          ' deactivate the form
              Set frm = Nothing   ' remove from memory	
        Next
    
  3. Have you ever wondered what events fire when you close a form? These events fire in this order:
    • Form_QueryUnload
    • Form_Unload
    • Terminate
    I feel you have the most control in the Form_QueryUnload event and that's my opinion.
        Private Sub Form_QueryUnload(Cancel As Integer, _
            UnloadMode As Integer)
    
        ' ---------------------------------------------------
        ' Cancel default is zero.  Setting Cancel to
        ' a non-zero value will stop all forms from unloading.
        ' ---------------------------------------------------
    
        ' ---------------------------------------------------
        ' Based on the the UnloadMode code
        ' the system passes, we determine what to do.
        ' Place your specific code under the
        ' appropriate case statement.
        ' ---------------------------------------------------
    
        Select Case UnloadMode
                Case 0:
                    ' User used the Control Box Menu in the upper
                    ' left corner or the "X" in the upper right
                    ' corner of the form.  If this is one of many
                    ' forms, I send it back to the form that called it.
                    ' One way in, one way out.
    
                Case 1:
                    ' Some other code within this application is causing
                    ' the shutdown.  Usually a routine in a BAS module.
    
                Case 2:
                    ' Windows session is closing (i.e. Start, Shut Down)
    
                Case 3:
                    ' Task Manager is closing this application.  (i.e.
                    ' Ctrl+Alt+Del, End Task)
    
                Case 4:
                    ' The MDI parent form is closing.
    
            End Select
        End Sub
    

Make a Program Run When Users Login
Put a shortcut to the program in Startup directory. In Windows NT this directory is:
    WinNT\Profiles\All Users\Start Menu\Programs\Startup
For an example program that shows how to create shortcuts programmatically, click here.

You can stop the program from starting automatically by removing the shortcut.

[Apparently the start menu is somewhere else in Windows 2000. Does anyone know how to find it reliably?]


Make a Program Run When the System Starts
There are several ways to use the Registry to make a program start when Windows boots. In each case, create a string value in the key giving it any name you want and set the value to the program's path.
  • To start your program after Windows logon, use the registry key:
    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
  • To start your program after Windows logon one time only, use the registry key:
    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
  • If your system makes you logon, use this key to run the program before Windows logon:
    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunServices
  • Similarly, use this key to run the program only once before Windows logon:
    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunServicesOnce
Thanks to Brady Doll.
Robert Heinig has this to add:

Run and RunOnce can also be used under HKCU, these entries are - of course - processed after all the others.

RunServices and RunServicesOnce are *ignored* under NT.

NT has its SCM, which is a bit too complex to cover here.

The order in which RunOnce enties are processed is sometimes important, there is a Microsoft KB article somewhere that states "in the order they were added", but that is definitely wrong under 98. I suspect this is correct for 95 and NT, because one project I did that depends on that succeeds on those and fails on 98, but this is not sufficient proof. I do suspect 98 does alphabetiacal order, but have no confirmation either.


Start a Program by Double Clicking
When you double click on a file in Windows Explorer, the system looks up the program associated with that kind of file. For example, if you have Microsoft Word installed, your system probably uses it when you double click a .doc file.

You can change the program the system uses when you double click a file. For details, see the "Change Startup Extensions" topic on this page. In particular, you can make the system use a program you have written.

When your program starts in this way, it is passed the name of the file double clicked as a command-line parameter. Use the Command$ statement to see what file was clicked.

The user can also start your program by dragging files onto your executable program. In that case, the files are also passed in as command-line parameters so you should use Command$ to see which files were dragged onto your program.


Add Files to an Installation Kit
To add extra files to a program's installation kit, follow these steps.
  1. Run the Setup Wizard (Packaging and Deployment Wizard in VB6) as usual.
  2. When you get to the file summary page, click the Add button to add the extra files.
  3. Click the File Details button. You will see a TextBox with a value that starts with "&(AppPath)." Change this to be the directory where the file placed. For example, to create a directory beneath the program's installation directory, change this to something like "&(AppPath)\Images."
  4. Repeat for the other files you want to add.
Thanks to James Rushing for digging out the details.
Change Startup Extensions
When you double click on a file in Windows Explorer, the system opens the file using a default application. To change the application used, follow these steps:
  1. In Windows Explorer, select the View menu's Options command. Click the File Types tab.
  2. Find the file type you want to change and select it.Click the Edit button.
  3. In the Actions list, click on "open" and then click the Edit button.
  4. The "Application used to perform action" field tells what application the system uses to open that kind of file. Change it to the new application.
If you are using a Visual Basic program to open the file, have the program use the Command$ statement to see what file was double clicked.
Start Programs With Drag and Drop
Suppose a user drags one or more files onto your program's name in Explorer or onto your program's icon. Windows starts your program passing it the names of the files that were dropped. Use the Command statement to find the names of the files.
Test Command Line Arguments
In VB5:
    Select the Project menu's Properties command (at the bottom). Click the Make tab and enter your arguments in the Command Line Arguments box.
In VB4:
    Select the Tools menu's Options command. Click the Advanced tab and enter the parameters in the Command Line Arguments box.

Always Unload Forms
Common folkwisdom is that End does not always clean everything up properly. People seem to get more reliable results by unloading all forms. I don't know if anyone knows exactly why (does anyone?) but lots of people have noticed strange behavior using End.

Theo Kandiliotis writes:

I remember working on a VB5 project that did a lot of sequential access writing to ASCII files. Several different procedures had Open statements but not all had Close statements. If the program ended with End and I hadn't used Close for a file I had used Open for, I couldn't erase that file from Windows Explorer. Windows thought the file was still active and was currently being used by another application, even though I had closed the VB application!
Jim Karabatsos Adds that End does not call QueryUnload so your program cannot ensure that data is safe. He says:
That means that files can be left open, object instances can be left orphaned and (in VB5) hooks and callbacks can be left pointing to invalid code. Only ever use END if you have a catastrophic failure (like the C: drive is dead). Otherwise, write yourself a Shutdown function like this:
   Public Sub Shutdown(Optional ByVal Force As Boolean = False)
      Dim I As Long

      On Error Resume Next

      For I = Forms.Count - 1 to 0 Step -1
         Unload Forms(I) ' Triggers QueryUnload and Form_Unload

         ' If we aren't in Force mode and the
         ' unload failed, stop the shutdown.
         If Not Force Then
            If Forms.Count > I then
               Exit Sub
            End If
         End If
      Next I

      ' If we are in Force mode OR all
      ' forms unloaded, close all files.
      If Force Or (Forms.Count = 0) Then Close

      ' If we are in Force mode AND all
      ' forms not unloaded, end.
      If Force Or (Forms.Count > 0) Then End
   End Sub
Tull Clancey Points out that other objects may need to be cleaned up as well. He writes:
...file handles, database controls, database objects, recordset objects, forms, and any other active links should be closed within a Form_Unload(x) procedure. If not done any links made will still be valid when the application is ended.

This is not always the case for the data control, however it is always good practice to close what you have opened. Mother always said put yesterdays toys away before playing with those today, very good advise!

An excellent point! While worrying about form closing problems, one shouldn't forget the basics.
Perform One-Time Initialization
Use a static variable to perform one-time initialization within a subroutine.
    Private Sub GetValue()
    Static initialized As Boolean

        If Not initialized Then
            ' Perform one-time initialization.
                :
            initialized = True
        End If
 
        ' Do other stuff.
            :
    End Sub

Send your Tips and Tricks to feedback@vb-helper.com.

 
Subscribe to the VB Helper newsletter
Copyright © 1997-2001 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
www.vb-helper.com/tips3.htm Updated