What's New
Q & A
Tip Jar
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


Resources During Development
By Bill Matthews

This is a hint which might be worth passing on to your readers. It was something I've looked at on a daily basis and have grumbled about for the last 6 months as I've worked on my program in the VB IDE.

My computer's resources were getting low enough that it was adversely affecting my switching between windows. Screen-updates were unbearably slow.

Finally, it dawned on me. My having all of the windows open, as I operate the IDE in the MDI mode, was not a problem when the program was small, but now I had to close some of them. When I did, of course the available-resources level increased.

Customize MSDN Help
(By Joe Hart)

In reference to using the help system...

It is not that difficult to use if you build a subset of just the Visual Basic areas. To do this, go to the View menu in MSDN, then click the last item, Define Subset. There you can choose the areas you would like to include. Once the subset is defined, you can select that subset, and then only those items that are in the subset you defined will be shown. This way you can strip out all of the C++, Java and other items that are not relevant to Visual Basic. I would suggest leaving the Knowledge Base in though as that can be very handy.

How to Hack an EXE File
(By Ariel Canievsky)

Could you edit an executable file when it has been compiled? Yes, you could. But you could only change the String data. How? Using the MS-DOS Text Editor. The String data is text, but in the file will appear different. For example, if in the application appears

    About NotePad
in the compiled file will appear
    A b o u t   N o t e P a d
with an space between each word. [This looks like 2-byte unicode characters. - Rod]

Before modifying the file, make a back-up of it. If you want to modify the file, first you have to open it using the MS-DOS Text Editor and open the file as Binary. Then activate the Insert key and search for some text data in the program. But, it isn't as easy as said. You have to search it mannualy, 'coz the words are separated by a space between. Then replace each word for anyone you want. Example:

    N o t e P a d
    M y P r o g r
BE CAREFUL: the file must weight the same than the original; if not, it could not work.

[Even then the file may not work. For example, it might calculate its checksum and notice that you have made changes.

This is certainly a dangerous technique. You should at least make a backup copy of the file before you mess with it. - Rod]

Arial adds:

You can use an hexadecimal file editor, such as HeXtreme. But, if you don't wanna complications, try to download ResHacker. This last one gives you the oportunity to modify not only text data from a program file, but picture resources as well. Even you can resize, changes menues, modify controls such as buttons and texboxes, or change/add key shortcuts.

Peter Chamberlin adds:

Regarding changing compiled executable files, you can indeed do editing via a hex editor or such, and most strings will indeed be in the 2 byte Unicode format, but there are dedicated programs out there that do this job quite nicely, and of course allow the whole PE to be modified. This means that any text strings can be changed to variable lengths, the graphics altered, the program description changed, etc. I've used this to great effect on <program name deleted> to rid myself of those pesky adverts :) and I've also made myself an updated Win98 Notepad.exe program so that the Select All menu item has a Cltr-A accelerator. Anyway, the URL for one of the programs is... ResourceHacker.

Thought you might like to share that with other people as I've found it an invaluable tool on many occasions.

Nexus adds:

Try using "Hiew" for editing binary files, such as executables. Official home page seems to be Hiew. Registration site is at shareit.

Bert Guffens adds this useful tip about building a VB program that you can modify after compiling:

Alltough the proposed method is indeed not without danger that the file may no longer execute there is a much better way, depending what you want to accomplish. You can simply open the .EXE file in Visual Basic (any version) and pad it with an empty string of any length needed to put some information. In that string you can then embed whatever you want and retrieve that information from within your program. For example, I usually put a 30 byte string at the end of the program, in the first byte (of those 30) I put a pointer indicating the file was patched. In the next 8 bytes (long integer) I put the file's current length (after the patch), and after that additional information whatever you like (even encrypted).

In my program there is a module that opens the file in binary mode (via buffer #9), looks at the EOF(9) - 29 at the pointer to see if the file was patched, if it is, I get the next 8 bytes to get the old file size and compair it with the current length. If they are not the same, a virus may have infected the .EXE, a warning message is displayed and the program ends. You may even in this case add a routine to overwrite the entire file with blanks and delete it.

This may not be a novel way of adding security, but it allows you to add (even scrambled) messages as to whether the program is registered or not. Note that the addition is not limited to 30 bytes and the program will always execute. You only need a small program for padding the file, the rest must be unscrambled from within your program but is only a standard subroutine you can use in all your programs.

[A similar technique adds a checksum to the file. Then you can not only tell if a virus has changed the length of the file, but you can also tell if someone has modified the file but kept the length the same. Rod]

Chris Wagg adds this:

I'd like to get my 2-cents in on hacking a binary file (since the "cat is already out of the bag" ;-). You can do it with VB! Create a new VB project and add a RichText Object. The code is up to you, but this *simple* example works: Add 2 buttons, then change the RichTextBox properties (OLE Drop Mode) to "Manual", and (optionally) set the font to a DOS/OEM font. I used the "Terminal" Font since most characters or bytes are represented instead of what appears to be "blanks" or spaces that aren't spaces. Here's the code: (you can Paste it in directly)

    Private Sub Form_Load()
        Command1.Caption = "Open"
        Command2.Caption = "Save"
    End Sub

    Private Sub Command1_Click()
        ' Open
        r = Shell("Explorer.exe", vbNormalFocus)
    End Sub

    Private Sub Command2_Click()
        ' Save
        If Len(RichTextBox1.FileName) Then
            RichTextBox1.SaveFile RichTextBox1.FileName, rtfText
        End If
    End Sub

    Private Sub RichTextBox1_OLEDragDrop(Data As RichTextLib.DataObject, _
        Effect As Long, Button As Integer, Shift As Integer, _
        x As Single, y As Single)

        ' Drag ANY file from the Explorer, or an "Explorer View"
        If Data.GetFormat(vbCFFiles) Then
            RichTextBox1.LoadFile Data.Files(1), rtfText
        End If
    End Sub
It is NOT true that you can't change the size of any binary file. And there's good reasons for editing a binary. For example, I ripped some MP3's, but on some songs - like the last song on the CD - the length is something like 20 minutes or longer. Actually the song is only 5 minutes long, with 15 minutes of silence! So I opened up the song with VB and the RichTextBox, found the silence, then hacked it out. The song plays better now!

Like you said before, make please a backup before proceeding to "hack" a file! Also you have to know something about a file's structure before modifying its content. If you don't what you're doing, please don't attempt "hacking a file"!

Some precautions about using a RichText object:

  • Avoid using the Clipboard, implicitly with keystrokes or explicitly with code. It could corrupt the file or the newly pasted text!
  • Avoid RichText operations, implicitly with keystrokes, or explicitly with code. For example, dragging and dropping text could corrupt the file!
  • If you want to enter some characters or bytes that aren't on the keyboard, try this: Hold down <Alt>, then enter the 4-digit decimal value. For example, to get FF entered: type <Alt> <0255>, then let up on <Alt>.
  • Null characters or bytes (&H0) look like spaces, but they really aren't spaces! So be careful editing these bytes. Also I haven't found a way to enter Hex 0 via the keyboard yet (or anything below a space).

Displaying Time in Hundredths of Seconds
You can display the time including hundredths of seconds using:
    txt = Format$(Time, "hh:mm:ss") & Format$(Timer - Fix(Timer), ".00")
Note that the Timer function does not have the resolution to measure time in hundredths of seconds so this may imply a false level of accurracy. (I think I remember hearing that Timer's resolution is 50 milliseconds).
Installing Registry Entries

Here's an easy way to set registry entries when you install a program. First, create the entries manually on your computer. Put them in their own subtree if possible. Use the registry editor to export the subtree containing the entries. This will creates a .REG file. Include this in the list of files given to the Package and Deployment Wizard. The Wizard will automatically offer to run the registry file on the target system during installation and that installs the registry values. Thanks to Bill Giuffre.

Learn ASCII Codes
(By Bill Mosca)

Ever want to know what the chr number is for a character? Open the immediate window and type

and press enter. The result will appear right before your very eyes.

Example: the number for a double quote


Make New Project Templates
When you select the New Project command from Visual Basic's File menu, you get a bunch of choices. You can add new choices quite easily.

First, start a new project. Get it loaded the way you want. Add controls to the toolbox, give it multiple forms and modules, add controls to the forms, place code in the forms and modules, etc. Do whatever you like that you can do in a normal project.

Next, save it all in your the Projects directory. I'm not sure where this directory is for all systems. On mine (WindowsNT/VB6), it's:

    C:\Program Files\Microsoft Visual Studio\Vb98\Template\Projects
Look for the template directory and then look inside for the Project directory. Save the project in there. Give the files meaningful names. Now when you select New Project from the File menu, the name of your project should appear in the list.
Disabling Windows
People keep asking how to disable Windows. For example, some people want to allow a program to take total control over the computer and not allow the user to switch to another application. That means preventing Ctl-Alt-Del from working, and stopping Alt-Tab from switching processes.

This goes strongly against one of the fundamental principles of Windows: that the user should always be in control. It takes control away from the user. It would also allow naughty people to create password grabbers and lock a computer against the user's wishes.

In Windows 95 you can disable Ctrl-Alt-Del and Alt-Tab using the SystemParametersInfo API function. This does not work in Windows NT (I don't know about Windows 98). For the reasons above, I suspect it will be hard or impossible to do this in Windoes NT. This is unfortunate because I know there are some legitimate reasons why a computer might want to do this. For example, in some other operating systems, you can specify a program for the computer to run when it boots. Unless you have system privileges, you cannot stop the program or switch to another.

Jarmo Lepola wrote an interesting program that locks the computer until the user enters a password ("mouse" in the example program). In Windows NT, the program grabs the focus many times per second so the user cannot do anything useful until entering the password. [Download it]

A few other people also suggested using SystemParametersInfo including:
Marc Strother
James Wilson

Thanks for the suggestions!

Making Help Files
This is generally a very hard topic. The Help Compiler Workshop comes with Visual Basic. Look for it in the Tools\Hcw or Common\Tools\Hcw directory on your Visual Basic CD-ROM.

The idea is you create a topic file containing the text of the help. You use an arcane set of footnotes defined by Microsoft to indicate links, topic titles, index entries, etc. You save this file in RTF (Rich Text Format), a format supported by many advanced editors including Word.

Next you create a project file that defines some topic numbers and identifies the help source file(s). You run the help compiler to produce the finished .HLP file.

Finally, your program can use the CommonDialog control's ShowHelp method to display the help file. To see an example program that does this, go to http://www.vb-helper.com/howtobeg.htm and click the "Implement standard File and Help menu commands" link.

All in all, creating help is quite difficult. The help compiler itself is unfriendly and slow, particularly for large help files. If you have an error, the compiler is uninformative. The Help Compiler Workshop puts a front end on some of the process, but it's still hard. Some third party help systems make things easier.

My book Advanced Visual Basic Techniques contains some information on building a help file. I do not know of a book that covers only help, though there are a few introductory books that cover help to some degree.

You might also consider HTML help. Microsoft is pushing it as the method of the future. That does not mean traditional help will go away any time soon, however. I don't know how to create Microsoft's fancy compressed help files (they probably have a tool), but you can easily create your own HTML pages with hyperlinks to provide a quick and easy help system. Advanced Visual Basic Techniques also discusses this method.

Null, Empty, Nothing, and vbNullString
These strange values have slightly different meanings.
  • Null. Null is a Variant subtype like Integer or String. It represents a variant that contains no valid data. This is different from zero, Nothing, Empty, or vbNullString. Most other values when combined with Null produce a Null result. For example:
        Null - Null      is Null not 0
        Null + 7         is Null not 7
        Null = Null      is Null not True
    You can use IsNull to determine whether an expression is Null:
        If IsNull(my_variable) Then ...
  • Empty. This is a variant subtype like Integer or String. It represents a variable that has not yet been initialized. This is different from Null which represents a value that specifically contains no valid data.

    A variant variable that has not yet been initialized has the value Empty. You can use IsEmpty to see if a variant has been initialized.

        If IsEmpty(my_variant) Then ...
  • Nothing. This is an object reference that points to no object. Set an object reference to Nothing to free that reference. If no other references point to the object, Visual Basic will destroy the object.
        Dim obj As Form1
            Set obj = Nothing ' Free the object reference.
    Use Is Nothing to determine whether a reference points to nothing:
        If obj Is Nothing Then ...
  • vbNullString. This constant represents an empty string. This is not the same as a blank string "". It is a nothing string. It is treated as an empty string "" for most Visual Basic purposes. Its real use is for passing null parameters to library functions.
Null is a strange value. It is not zero, it is not Nothing, it is not the same as vbNullString. It is something undefined.
See if a String is Blank
There are several ways to decide whether a string is blank:
    Dim txt As String
    Dim blank As String

        blank = ""
        If Len(txt) = 0 Then ...
        If txt = vbNullString Then ...
        If txt = "" Then ... 
        If txt = blank Then ...
The test Len(txt) = 0 is roughly 20 percent faster than the others.
Search for the last occurrence of a pattern in a string
In Visual Basic 6, use InStrRev. In earlier versions, try this function:
    Function LastInStr(txt As String, pattern As String)
    Dim pos1 As Integer
    Dim pos2 As Integer

        pos2 = 0
            pos1 = pos2
            pos2 = InStr(pos1 + 1, txt, pattern)
        Loop While pos2 > 0
        LastInStr = pos1
    End Function

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/tips13.htm Updated