Beruflich Dokumente
Kultur Dokumente
OpenFile Function
The OpenFile function can be used to perform several file operations, such as creating a
new file, deleting a file, or determining if a file exists. To declare this function within
your program, include the following Declare statement in the Global Module or General
Declarations section of a Visual Basic® for Windows® form:
Declare Function OpenFile% Lib "Kernel" (ByVal lpFileName$, lpReOpenBuff
As OFSTRUCT, ByVal wStyle%)
Note that this Declare statement must be typed as one single line of text.
The OpenFile function takes the following arguments, described as follows:
Argument Description
lpFileName A string containing the name, which may or may not include a path
name, to test.
lpReOpenBuff An OFSTRUCT structure that will contain information about the file
after the OpenFile function has been called.
wStyle This combination of one or more flags specifies the type of operation
that is to be performed on the file.
In our demonstration program, we need only specify wStyle as the constant OF_EXIST.
After calling the OpenFile function, an integer value is returned. If a negative number is
returned, the nErrCode value in the OFSTRUCT structure can be examined to find out if
the file exists already.
Example Program
However, if a user clicked the Cancel command button in the dialog box, your program
must be able to process this condition appropriately so that special error conditions can be
monitored. The CancelError property of the dialog box provides a method of error-
checking in your applications.
Let's assume that you want to include the Color dialog box in your own application
program. First, you would draw a common dialog control on your form. When your
program is executed, the common dialog control is invisible. Therefore, you can place the
control anywhere on your form because it won't interfere with your program's
appearance. Also, note that you need only place one common dialog control on your form
to call any or all of the six dialog boxes—you don't need a separate control for each type
of dialog box you want to display.
Next, you set the Action property of the common dialog control to specify which dialog
box you want to use. If you want to call up the Color dialog box, for example, you would
set the Action property to a value of 3.
When you execute your application program, you set values for the various properties of
the dialog box you are using. Once the Action property statement is executed at run time,
the dialog box will be displayed on your form. After the user has clicked the dialog box's
OK command button, your program regains control and you can test the various options
the user selected in the dialog box.
To prevent errors from occurring in your application, such as specifying a nonexistent
color in the Color dialog box, you can use the CancelError property. This property lets
you know if the user clicked the Cancel button on the dialog box. Each of the six dialog
Example Program
The following program demonstrates how you can set a trap to find out if the user pressed
the Cancel button of a dialog box.
When you place controls on a form, the TabIndex property determines which control
will receive the focus next. The control with the next highest TabIndex value
automatically receives the focus.
You can place a Label control, which has a Caption property, in front of a control that
cannot receive the focus, such as a Text Box. Because a Label control cannot receive the
focus, the next control in the TabIndex order receives the focus.
Let's assume that you want to assign an access key to a Text Box. First, you would draw
a Label control on your form and set its Caption property so it is assigned an access key,
for example, &Name. Next, you would add a Text Box control beside or near the Label
control. Make sure the TabIndex value of the Text Box is one greater than that of the
Label control.
When your application program is running, you can move the focus to the Text Box by
pressing the access key assigned to the Label control.
You must remember that this technique will only work as long as the TabIndex property
of the Label control is always one less than the control you want to actually move the
focus to.
The SystemParametersInfo function can also be used to remove the Desktop wallpaper
so that no wallpaper will be used at all.
The following program retrieves the contents of the AUTOEXEC.BAT file and displays
it in a multiline text box.
Example Program
1. Start a new project in Visual Basic. Form1 is created by default.
To change the visibility status of a window with the ShowWindow function, you must
first determine the window's handle. In our case, we need to retrieve the handle for
Program Manager. This can be accomplished by calling the FindWindow function.
To declare the FindWindow function within your program, include the following
Declare statement in the Global Module or General Declarations section of your form:
Declare Function FindWindow Lib "User" (ByVal lpClassName As Any, ByVal lpWindowName As Any)
As Integer
To call the FindWindow function, you must pass it two arguments, as follows:
lpClassName A string (or long pointer to a string) that contains the window's class
name. A value of zero is used to accept any class.
lpWindowName A string (or long pointer to a string) that contains the window's title bar
text. A value of zero is used to accept any window title.
Because we want to minimize (or maximize) Program Manager to an icon, we would call
the FindWindow function with the following statement:
hWnd = FindWindow(0&, "Program Manager")
The window's handle will be returned in the hWnd variable. We can then call the
ShowWindow function to minimize or to maximize Program Manager with these two
statements:
I = ShowWindow(hWnd, SW_SHOWMINNOACTIVE)
I = ShowWindow(hWnd, SW_RESTORE)
Example Program
The following program shows how to minimize and maximize Program Manager from
within a Visual Basic application.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that each Declare statement must be typed as a single line
of text):
3. Declare Function ShowWindow Lib "User" (ByVal hWnd As Integer, ByVal nCmdShow
4. As Integer) As Integer
5. Declare Function FindWindow Lib "User" (ByVal lpClassName As Any, ByVal
6. lpWindowName As Any) As Integer
7. Const SW_SHOWMINNOACTIVE = 7
8. Const SW_RESTORE = 9
9. Add a Command Button control to Form1. Command1 is created by default. Set
its Caption property to "Minimize PM".
10. Add the following code to the Click event for Command1:
11. Sub Command1_Click()
12. Dim hWnd As Integer, I As Integer
13.
14. hWnd = FindWindow(0&, "Program Manager")
15. If hWnd <> 0 Then
16. I = ShowWindow(hWnd, SW_SHOWMINNOACTIVE)
17. End If
18. End Sub
19. Add a second Command Button control to Form1. Command2 is created by
default. Set its Caption property to "Maximize PM".
20. Add the following code to the Click event for Command2:
21. Sub Command2_Click()
22. Dim hWnd As Integer, I As Integer
23.
24. hWnd = FindWindow(0&, "Program Manager")
25. If hWnd <> 0 Then
26. I = ShowWindow(hWnd, SW_RESTORE)
27. End If
28. Form1.SetFocus
29. End Sub
When you execute this demonstration program, click on the "Minimize PM" command
button to make Program Manager a minimized icon on the desktop. Click on the
"Maximize PM" command button to restore Program Manager to its default size.
This article explains how you can delete a specific entry from an .INI file. For a detailed
description of Windows initialization files and the API functions you can use to modify
them, see the "Additional References" section at the end of this article.
1. Using the Windows Notepad application, create a new text file called DEMO.INI.
Save the file to the root directory on drive C. Add the following lines to this text
file:
2. [progsetup]
3. Date=10/10/95
4. Datafile=c:\temp.dat
5. [colors]
6. Background=red
7. Foreground=white
8. Start a new project in Visual Basic. Form1 is created by default.
26. Add a command button control to Form1. Command1 is created by default. Set its
Caption property to "Modify DEMO.INI".
Abstract
Visual Basic® allows you to add Command button controls to your application programs.
Command buttons can display a one-line caption (up to a maximum of 255 characters in
length) that tells users of your program the command that will be executed when they
click the mouse on the button. However, you can have the same functionality if you
create a multiline command button using the Picture Box control.
After you have calculated the values for the CurrentX property, you must issue the Print
command to tell Visual Basic to draw the text on the Picture Box control. To do this, you
execute the statement:
Picture1.Print Msg
Example Program
The following program demonstrates how to create a multiline Command button in
Visual Basic.
1. Start a new project in Visual Basic. Form1 is created by default.
Abstract
This article explains how you can format a diskette in a floppy drive from within a Visual
Basic® application. Microsoft® Windows® does not provide any functions to format a
diskette, but it can be done by using the WinExec application programming interface
(API) function.
Formatting Disks
The Windows® WinExec application programming interface (API) function can execute
any Windows-based or non-Windows-based program. To call the WinExec function, you
must first add its Declare statement to the Global Declarations section of your Visual
Basic® application. Following is the WinExec function declaration:
Declare Function WinExec Lib "Kernel" (ByVal lpCmdFile As String, ByVal
fuCmdShow As Integer) As Integer
(Note that this Declare statement must be typed as a single line of text.)
To execute a program, you would call the WinExec function with the statement:
x = WinExec(lpCmdFile, fuCmdShow)
specifying the following parameters:
lpCmdFile \A string containing the name of the application to execute
fuCmdShow \An integer value that tells WinExec how to show the application
\when it is executed. This may be one of the following constants:
SW_HIDE \The window is hidden and activation passes to another window.
SW_MINIMIZE \The window is minimized and activation passes to another
\window.
SW_RESTORE \The window is activated and displayed in its original size and
\at its original location.
SW_SHOW \The window is activated and displayed in its current size and
\at its current location.
SW_SHOWMAXIMIZED \The window is maximized and activated.
SW_SHOWMINIMIZED \The window is minimized and activated.
SW_SHOWMINNOACTIVE \The window is minimized but the active window is not
\changed.
SW_SHOWNA \The window is displayed at its current location in its current
\size but the active window is not changed.
SW_SHOWNOACTIVATE \The window is displayed at its most recent location in
\its most recent size but the active window is not
\changed.
SW_SHOWNORMAL \The window is activated and displayed in its original
\size and at its original location.
After the WinExec function is called, it returns an integer value greater than 32 if the
application was successful. Otherwise, one of the following error codes is returned:
The lpCmdFile argument must be a string containing the name of the application
program you want to execute, as well as any command line parameters required by the
application program itself. If the argument does not include the full path, Windows will
search for the application in the following order:
1. The current directory
6. Network directories
As stated earlier, the WinExec function can execute any Windows-based or MS-DOS®–
based program. This includes .EXE, .COM, and .BAT files. In addition, WinExec can
also be used to execute Windows screen savers (files that have the .SRC file extension)
and program information files (files that have the .PIF file extension). Windows is
shipped with several .PIF files that you can use in conjunction with the WinExec
function. One of these files is called DOSPRMPT.PIF. This particular .PIF file contains
information that Windows needs to run an MS-DOS program. The .PIF file tells
Windows, for example, how much memory should be set aside to run the MS-DOS
program.
This problem is easily solved. To respond to the prompts from the FORMAT command,
we first need to create a file called RESPONSE.TMP. This file contains the keystrokes
we want to pass on to the FORMAT command, just as if we had typed them at the
keyboard ourselves. DOS's redirection capabilities will allow us to pass the contents of
the RESPONSE.TMP file to the FORMAT.COM program.
Example Program
The following program formats a floppy disk in drive B.
1. Start a new project in Visual Basic. Form1 is created by default.
2. In the General Declarations section of Form1, add the following three statements:
3. Const Resp_File = "c:\response.tmp"
4. Const SW_HIDE = &H0
5. Dim ActiveApps As Integer
6. In addition, add the following two Declare statements (note that each statement
should be typed as a single line of text):
7. Declare Function WinExec Lib "Kernel" (ByVal lpCmdLine As String, ByVal nCmdShow
8. As Integer) As Integer
9. Declare Function GetNumTasks Lib "Kernel" () As Integer
10. Add a command button control to Form1. Command1 is created by default. Set its
Caption property to "Format Disk".
Abstract
You can determine the name of your application as well as the directory where the
program is stored on your disk. This is useful when a user has renamed your application
or when you want to determine where your application can store its own temporary files.
Example Program
The program below shows how you can retrieve an application's filename and path in
Visual Basic®.
1. Start a new project in Visual Basic. Form1 is created by default.
3. Add the following code to the Click event of the Command1 command button:
4. Sub Command1_Click()
17. Add the following code to the Click event of the Command2 command button:
18. Sub Command2_Click()
19. End
20. End Sub
21. Save the project to disk using the filename TEXT.MAK. Create an .EXE program
file in the root directory of drive C (C:\TEST.EXE).
22. To execute this program, exit Visual Basic. Next, from Program Manager, click
on File/Run. Type the name of the program to run as C:\TEST.EXE and click the
OK command button.
After Windows launches TEST.EXE, you can click the "Execute Notepad" command
button. The Windows Notepad application will be executed and will load your
AUTOEXEC.BAT file. Next, TEST sends the ALT+SPACE+X keystroke combination
to Notepad to maximize that application's window. TEST's program name and path are
then stored in two string variables and, when the ALT+SPACE+C keystrokes are sent to
Notepad to terminate that program, TEST displays the full path of TEST.EXE in its Text
Box. Clicking the "Exit" command button terminates the demonstration program.
Abstract
When you execute a DOS program through the Visual Basic® shell command, the only
way you can use the redirection capabilities of DOS is to save the DOS program output to
To use the GetNumTasks function in your Visual Basic applications, include the
following Declare statement in the Global Module or General Declarations section of
your form:
Declare Function GetNumTasks Lib "Kernel" () As Integer
Note that this Declare statement must be typed as one single line of text.
The GetNumTasks function does not require any arguments; you simply call it. It returns
an integer value set to the number of tasks that are currently running.
Example Program
This program creates a batch file that contains the DOS command "DIR C:\*.* >
C:\DIRLIST.DAT". This batch file tells DOS to issue a dir command on drive C and
send the output of that command to the text file called DIRLIST.DAT. The Visual Basic
program then displays the contents of DIRLIST.BAT in the Text Box.
1. Start a new project in Visual Basic. Form1 is created by default.
Abstract
Assume that you are writing a program where some kind of event has to be timed. You
retrieve a time value representing the total number of seconds the event took to process
its work. The problem is that you want to convert this seconds value to its equivalent
minutes and seconds value and display that string to the user. The Visual Basic® Mod
operator can do this conversion process for you.
Example Program
The following program demonstrates how you can use the Mod operator to convert a
number representing a time value to a string.
1. Start a new project in Visual Basic. Form1 is created by default.
2. Add a Label control to Form1. Label1 is created by default. Set its Caption
property to "Enter a value:".
3. Next to Label1, add a Text Box control. Text1 is created by default. Set its Text
property to a NULL (empty) string.
12. Beside Label2, add a Text Box control. Text2 is created by default. Set its Text
property to a NULL (empty) string.
13. Add a Command Button control to Form1. Command1 is created by default. Set
its Caption property to "Exit".
14. Type the following code in the Click event for Command1:
15. Sub Command1_Click()
16. End
17. End Sub
When you execute this Visual Basic application, enter a value in the first text box. Press
the TAB key to move to the second text box. The program will convert the value you
entered to a string representing that value in minutes and seconds. Click on the Exit
command button to terminate the program.
Abstract
One of the nice features provided under Windows® 3.1 is its Clipboard. Data (text or
graphics) can be copied from an application program to the Clipboard. This data can then
be transferred from the Clipboard to a different application, to be processed in some way.
This article shows how you can copy selected items from a List Box control to the
Clipboard. The Clipboard.GetText command copies information from the Clipboard to an
object, such as a Text Box. Conversely, the Clipboard.SetText command copies
information from an object to the Clipboard.
Example Program
The following Visual Basic® application copies selected items from a List Box control to
the Clipboard.
10. Draw a Text Box control under the List Box control. Text1 is created by default.
Set its MultiLine property to True and its ScrollBars property to 2-Vertical.
11. Add a Command Button control to Form1. Command1 is created by default. Set
its Caption property to "Copy to Clipboard".
12. Type the following code in the Click event for Command1:
13. Sub Command1_Click()
14. Dim CopytoClip As String
15. Dim I As Integer
16. Clipboard.Clear
17. CopytoClip = ""
18. For I = 0 To List1.ListCount - 1
19. If List1.Selected(I) Then
20. CopytoClip = CopytoClip & Form1.List1.List(I) & Chr$(13) & Chr$(10)
21. End If
22. Next I
23. Clipboard.SetText CopytoClip
24. End Sub
25. Add a Command Button control to Form1. Command2 is created by default. Set
its Caption property to "Show Clipboard".
26. Type the following code in the Click event for Command2:
27. Sub Command2_Click()
28. 'display data stored in clipboard
29. Text1.Text = ""
30. Text1.Text = Clipboard.GetText(CF_TEXT)
31. End Sub
32. Add a Command Button control to Form1. Command3 is created by default. Set
its Caption property to "Exit".
33. Type the following code in the Click event for Command3:
34. Sub Command3_Click()
35. End
36. End Sub
Abstract
Visual Basic® has three file system controls: the Drive List Box, the Directory List Box,
and the File List Box. Using these three controls, a Visual Basic application can access
every file stored on a floppy, fixed, or network disk drive.
30. Add the following code to the Change event for the Dir1 Directory List Box
control:
31. Sub Form_Load()
32. Next_Dir = 0
33. Temp_Dir = "C:\"
34. Dir1.Path = Temp_Dir
35. Temp_Dir = List2.List(Next_Dir)
36. Get_Next:
37. Next_Dir = Next_Dir + 1
38. Dir1.Path = Temp_Dir
39. Temp_Dir = List2.List(Next_Dir)
40. If List2.ListCount - 1 = Next_Dir Then
41. Exit Sub
46. Add a second List Box control to Form1. List2 is created by default. Set its
Visible property to True, its MultiSelect property to 1-Simple, and its Sorted
property to True.
When you execute this program, Visual Basic will search for all subdirectories on the
drive C. This may take a few moments to do, depending on the size of the hard disk and
the number of directories the application finds. The name of each subdirectory will be
displayed in the List Box, in alphabetical order.
Abstract
You can make your Visual Basic® applications more attractive and professional looking
if you include a splash screen. Splash screens are simply forms that are displayed as soon
as your application program is executed.
Splash screens are used to display important information (such as copyright notices) to
users when the application is first executed. Sometimes, splash screens are presented to
users while the application is performing time-consuming operations.
Example Program
2. Add a Picture Box control to Form1. Picture1 is created by default. Set its Picture
property to a bitmap, such as that provided in
C:\VB\BITMAPS\ASSORTED\HAPPY.BMP.
3. Add a Text Box control to Form1. Text1 is created by default. Set its Text
property to "Splash Screen Demo". Set its BorderStyle property to 1-Fixed
Single.
5. Create a new project in Visual Basic. Form1 is created by default. Set its Caption
property to "VB Splash Screen Demo".
12. Create a New Module file and name the module SPLASH.BAS.
Abstract
The mouse pointer, or mouse cursor, as it is often called, can be temporarily toggled on
or off within a Visual Basic® application. You might want to make the cursor invisible
while your program displays a maximized form that contains a graphic picture. Then,
after displaying the graphic, you can make the cursor visible again. The Windows®
application programming interface (API) ShowCursor function lets a Visual Basic
program hide the cursor from view.
The ShowCursor function requires only one argument. When bShow is set to TRUE, the
cursor is displayed; when bShow is set to FALSE, the cursor is hidden.
You cannot simply call the ShowCursor function to hide the cursor. You also need to be
aware that the cursor's visibility depends on the value of an internal display count that
Windows maintains. This count value is incremented by a value of one each time
ShowCursor is called with bShow set to TRUE. Conversely, each time ShowCursor is
called with bShow set to FALSE, the count value is decremented. When the count value
is greater than or equal to zero, the cursor is displayed.
Example Program
The following program demonstrates how to make the cursor invisible and how to make
it reappear in a Visual Basic application program.
Abstract
When moving the focus from a control to a Text Box, the text is not selected when the
Text Box receives the focus. However, you can do this automatically in your program.
When a program moves the focus to a Text Box, the caret is placed at the beginning of
the actual text in the control. In an application, you may want to select the text in some
situations, such as when you press the TAB key to move to the Text Box. This can be
accomplished by using the Windows® GetKeyState application programming interface
(API) function in conjunction with the SelLength and SelStart properties of the Text
Box.
Example Program
The following program demonstrates how you can select text in a Text Box when the
TAB key is used to move the focus to that control.
When using the Graph custom control in a Visual Basic® application, you can change the
GraphType property at run time.
To change the GraphType property successfully in an application, you must first execute
a DrawMode statement, and then execute the statement that changes the GraphMode
property. Therefore, you would first call the following statement in your Visual Basic
application:
Graph1.GraphType = 1
Abstract
In a Visual Basic® application, you may want to disable the SHIFT+PRINTSCRN
keystroke combination. This can be accomplished by trapping the key in a control or
form's KeyDown event.
Example Program
Abstract
Many Windows®-based applications can be written so that, when executed, they are
shown on the desktop simply as an icon. These type of programs usually perform some
kind of background task and are never maximized because no user input is required.
Double-clicking an icon automatically tells Windows to maximize the application's
window to a full-screen display. This article tells you how to create iconized applications
in Visual Basic® that cannot be maximized.
• The window is displayed as normal (the default setting). This is the size you made
the window when designing the application in Visual Basic®.
Example Program
The following program creates a Visual Basic application that is minimized to an icon
when it is executed. To terminate the program, double-click its icon.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following code to the Form_Load event for Form1.Sub Form_Load():
3. WindowState = 1
4. End Sub
5. Add the following code to the Form_Resize event for Form1:
6. Sub Form_Resize()
7. If WindowState <> 1 Then
8. WindowState = 1
9. End
10. End If
11. End Sub
12. From the Visual Basic File menu, select "Make EXE File" to create a stand-alone
.EXE program file.
13. Next, execute the program from Program Manager's Run command. The
program's icon will be displayed on the desktop. You cannot maximize this
window by double-clicking the icon; that will cause the application to be
terminated.
Abstract
You can write functions in Visual Basic® that split and combine DWords, Words, and
Bytes. These functions can be used to do such things as taking two integer values and
transferring them to a long integer value, where the first integer is the high word and the
second integer is the low word.
Abstract
Visual Basic® offers many functions that can convert values from one type to another.
One of these functions is CCur. This function will take a string variable containing a
The CCur function converts a number to a Currency type number—that is, a number that
can contain, at maximum, four digits after the decimal place. The variable passed to the
CCur function must be no larger than 8 bytes in length and must contain a fixed decimal
point.
By combining the Format and CCur functions, you can easily convert the number to a
rounded dollar amount with only two digits after the decimal point.
Example Program
The program below shows how to use the CCur function in a Visual Basic program.
When it is executed, this program displays the value 14.2399 in the first Text Box and its
properly formatted currency value, 14.24, in the second Text Box.
1. Start a new project in Visual Basic. Form1 is created by default.
2. In the General Declarations section of Form1, add the following two statements:
3. Dim Amount As Currency
4. Dim Total As String
5. Add the following code to the Form_Load event for Form1:
6. Sub Form_Load()
7. Amount = 14.2399
8. Text1.Text = Str$(Amount)
9. Total = CCur(Format(Amount, "#,##0.00"))
10. Text2.Text = Total
11. End Sub
You can avoid this error in your application program if you use a Do-While loop instead
of a For-Next loop. Each time through the loop, the X variable should be incremented by
a value of one. If this is done, the code will successfully remove all selected items from
the List Box.
Example Program
The program below shows how you can successfully remove all items that are selected
(highlighted) from a List Box. When you execute this program in Visual Basic, the List
Box will be filled with 16 items. Select several items to delete by clicking the mouse on
the items. When you're ready to actually remove these items from the List Box, click the
"Delete Selected Items" command button. After a second or two, the List Box will
display only those items that were not previously selected.
1. Start a new project in Visual Basic. Form1 is created by default.
2. Add a List Box control to Form1. List1 is created by default. Set its MultiSelect
property to 1-Simple.
4. In the General Declarations section of Form1, type the following Dim statement:
5. Dim X As Integer
6. Add the following code to the Form_Load event for Form1:
7. Sub Form_Load()
8. For X = 0 To 15
9. List1.AddItem "Item #" & Str$(X)
10. Next X
11. End Sub
12. Add the following code to the Click event for Command1:
13. Sub Command1_Click()
14. X=0
15. Do While X < List1.ListCount
16. If List1.Selected(X) = True Then
Abstract
When you install a Windows®-based application on your hard disk, it creates its own
directory and copies its files to that directory. However, when you run the application, it
may need to create additional temporary data files of some sort. Where does the
application store these temporary files and how can your program retrieve this drive
number and/or path?
Example Program
The following program will retrieve the drive letter from the computer system.
1. Start a new project in Visual Basic. Form1 is created by default.
2. In the general declarations section of Form1, enter the following three statements
(note that the Declare statement must be typed as a single line of text):
3. Dim Drive As Integer
4. Dim DriveLetter As String
5. Declare Function GetTempDrive Lib "Kernel" (ByVal cDriveLetter As Integer)
6. As Integer
7. Add the following code to the Form_Load event for Form1:
8. Sub Form_Load()
9. Drive = GetTempDrive(0)
10. DriveLetter = Chr$(Drive And &HFF)
11. Text1.Text = DriveLetter
12. End Sub
13. Add a Text Box control to Form1. Text1 is created by default.
Abstract
When displaying text in a Visual Basic® program, you have the option of specifying that
the text be shown in different screen fonts. This also applies to text sent to the printer
Example Program
The program below displays three List Box controls on a Visual Basic form. Printer fonts
are listed in the first List Box, screen fonts in the second List Box, and those fonts that
are common to both the printer and screen in the third List Box.
Abstract
When developing an application in Visual Basic®, you may need to interrupt a time-
consuming function or react to a certain keypress. It is always a user-friendly option if
you allow your user to exit out of these long processes gracefully. The Windows®
GetAsyncKeyState application programming interface (API) function can be used to
detect when the user has pressed a certain key on the keyboard or clicked a mouse button.
The GetAsyncKeyState function determines if the specific key was pressed since the last
call to this function. It can also tell you if one of the mouse buttons was pressed. This
function takes only one argument—an integer value that represents the key code of the
virtual key or mouse button you want to test.
GetAsyncKeyState returns a non-zero value if the specified key or button is currently
pressed. It will also return a non-zero value if the key or button was pressed since the last
call to this function. The CONSTANT.TXT file contains a list of the virtual key
constants.
Example Program
The following Visual Basic program shows how you can perform a function within your
program until a specific keystroke is detected on the keyboard. In this example program,
the DoEvents function is called to put the program in a constant loop. When you press
the ESC (escape) key, the program is terminated.
1. Start a new project in Visual Basic. Form1 is created by default.
Abstract
A program created in Visual Basic® may contain many different forms. Forms can be
loaded into memory whenever they are required and removed from memory when no
longer needed. Sometimes you need to find out if a specific form is currently loaded. This
article provides a technique for determining if a form is loaded or not.
Example Program
1. Start a new project in Visual Basic. Form1 is created by default. Set its Caption
property to "First Form".
2. Create a second form. Form2 is created by default. Set its Caption property to
"Second Form".
3. Create a third form. Form3 is created by default. Set its Caption property to
"Third Form".
Abstract
When designing a MDI application in Visual Basic®, you first create the primary MDI
form and add secondary child forms to the MDI form. After your program is executed,
you can initially display the child forms as minimized icons. These icons will appear at
the bottom of the primary MDI form's window.
However, when the icons are displayed on the form, you can actually see each child form
quickly displayed in its normal size on the MDI form. This article explains how you can
prevent Windows® from flashing these child windows before they are shown as
minimized icons. The icons will be minimized immediately without this side effect.
To call the ShowWindow function, you pass the window's handle and the visibility status
you want to apply to the window. The visibility status may be one of the constants in the
following table.
SW_HIDE Window is hidden.
To change the visibility status of a window with the ShowWindow function, you must
first determine the window's handle. In our case, we need to retrieve the handle for the
child window. This can be done with the statement:
X% = Form2.hWnd
where Form2 is the name of the form whose handle we want to retrieve and the X
variable will contain the handle number. Every Visual Basic form has an hWnd property
that is set to the form's handle. Once the ShowWindow function is called, the child
window will be immediately iconized on the MDI form.
Example Program
The following program shows how you can display a MDI form's child windows as icons
without first having the child windows flashed on the MDI form in their normal size and
position.
4. Add a second child form to MDIForm1. Form3 is created by default. Set its
WindowState property to 1-Minimized. Set its MDIChild property to True.
6. Add the following Constant and Declare statement to the General Declarations
section of MDIForm1 (note that the Declare statement must be typed as one
single line of text):
Abstract
The WIN.INI initialization file contains many settings used by Windows® when it is first
loaded into memory. These settings tell Windows, among many other things, what type
of printer you have attached to the computer system. You can retrieve the name of the
printer from the WIN.INI file and use it in your Visual Basic® application. This article
explains how you can determine the printer's name.
To call the GetProfileString function, you must pass five arguments that describe which
section and entry of the WIN.INI file you want to retrieve information from. These
parameters are as follows:
lpApplicationName A string containing the section name. Not case-sensitive.
lpKeyName A string containing the entry name to retrieve. Not case-sensitive. If
this is a long value set to zero, a list of all entries found in the
specified section will be returned in lpReturnedString.
lpDefault A string containing the default value to return if no entry is found.
lpReturnedString A string buffer that will hold the information the function retrieves.
nSize An integer value set to the maximum number of characters to be
stored in lpReturnedString
After calling the GetProfileString function, an integer value is returned that is set to the
number of characters that were stored in the lpReturnedString buffer. This count value
does not include the terminating NULL byte. Each entry returned in lpReturnedString is
terminated by a NULL character. When retrieving more than one entry at a single time,
The last entry in the buffer is marked with two NULL bytes to signal the end of the list.
In our case, we want to call the GetProfileString function to retrieve the printer's name.
Therefore, we execute the following statement:
RC = GetProfileString("windows", "device", "", Temp, 255)
This statement tells GetProfileString that we want to retrieve the parameter for the
DEVICE entry in the WINDOWS section of the WIN.INI initialization. It also tells the
function to store the information in the Temp string buffer and that this buffer is set to a
maximum length of 255 characters.
Example Program
The following Visual Basic program shows how you can retrieve the name of the printer
from the WIN.INI initialization file.
1. Start a new project in Visual Basic. Form1 is created by default.
3. Add the following Declare statement to the general declarations section of Form1
(note that this Declare statement must be typed as one single line of text):
4. Declare Function GetProfileString Lib "Kernel" (ByVal lpAppName As String, ByVal
5. lpKeyName As Any, ByVal lpDefault As String, ByVal lpReturnedString
6. As String, ByVal nSize As Integer) As Integer
7. Add the following code to the Form_Load event for Form1:
8. Sub Form_Load()
Abstract
Windows® displays an image as its wallpaper. You can add this feature to your own
Visual Basic® programs. This article explains how you can use the Windows application
programming interface (API) BitBlt function to copy a single icon multiple times. The
icons are copied so that they cover the entire area of the form, giving it a "wallpaper"
look.
To declare this function within your program, include the following Declare statement in
the Global Module or General Declarations section of your form:
Declare Function BitBlt Lib "GDI" (ByVal hDestDC As Integer, ByVal X As Integer,
ByVal Y As Integer, ByVal nWidth As Integer, ByVal nHeight As Integer, ByVal
hSrcDC As Integer, ByVal XSrc As Integer, ByVal YSrc As Integer, ByVal dwRop
As Long) As Integer
The BitBlt function requires that nine arguments be passed to it. These arguments are as
follows:
hDestDC An integer value that contains the device context (hDC property) of the
destination device
hSrcDC An integer value that contains the device context (hDC property) of the
source device
X, Y Integer values that contain the upper-left corner in the destination where
the bitmap is to be placed. Specified in logical coordinates.
nWidth, Integer values that contain the logical dimensions of the bitmap.
nHeight
Xsrc, Ysrc Integer values that contain the logical coordinates of the source bitmap's
upper-left corner
dwRop A long value that specifies how the BitBlt function is to copy the bitmap.
The dwRop argument may be specified as one of the constants in the following table
(these values are stored in the CONSTANT.TXT file).
BLACKNESS All output is black.
DSTINVERT The destination bitmap is inverted.
MERGECOPY The Boolean AND operator combines the pattern and the source
bitmap.
MERGEPAINT The source bitmap is inverted and the Boolean OR operator is used to
combine it with the destination bitmap.
NOTSRCCOPY The source bitmap is inverted and copied to the destination bitmap.
NOTSRCERASE The Boolean OR operator is used to combine the source and
destination bitmaps. The resulting bitmap is then inverted.
PATCOPY The pattern is copied to the destination bitmap.
PATINVERT The Boolean XOR operator is used to combine the destination
bitmap with the pattern.
PATPAINT The Boolean OR operator is used to invert the source bitmap and
combine it with the pattern. The Boolean OR operator is then used to
combine the result with the destination bitmap.
SRCAND The Boolean AND operator is used to combine the pixels of the
source and destination bitmaps.
SRCCOPY The source bitmap is copied to the destination bitmap.
SRCERASE The Boolean AND operator is used to invert the destination bitmap.
The result is then combined with the source bitmap.
SRCINVERT The Boolean XOR operator is used to combine the pixels of the
source and destination bitmaps.
SRCPAINT The Boolean OR operator is used to combine the pixels of the source
We want to copy a bitmap many times so that the entire form is covered in bitmaps, so
we execute the following statement in a Visual Basic program:
D = BitBlt(hDC, X, Y, PatternWidth, PatternHeight, hDC, 0, 0, SRCCOPY)
The SRCCOPY constant tells the BitBlt function to copy the bitmap to the destination;
in this case we are copying it to the form.
Example Program
The following Visual Basic application displays a pattern over the entire area of a form.
This example program uses the ARGYLE.BMP bitmap file shipped with Windows. You
can substitute any other bitmap of your choice, as long as it is 32-by-32 pixels. This is
hard-coded into the demonstration program in the PatternWidth and PatternHeight
variables.
2. Set the Picture property of Form1 to the ARGYLE.BMP bitmap file (this file will
be located in the WINDOWS directory).
3. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that the Declare statement must be typed as one single line
of text):
4. Const SRCCOPY = &HCC0020
5. Declare Function BitBlt Lib "GDI" (ByVal hDestDC As Integer, ByVal X As Integer,
6. ByVal Y As Integer, ByVal nWidth As Integer, ByVal nHeight As Integer, ByVal
7. hSrcDC As Integer, ByVal XSrc As Integer, ByVal YSrc As Integer, ByVal dwRop
8. As Long) As Integer
9. Add the following code to the Paint event for Form1:
10. Sub Form_Paint()
11. Dim X As Integer
12. Dim Y As Integer
13. Dim D As Integer
14. Dim PatternHeight As Integer
15. Dim PatternWidth As Integer
16. Dim SM As Integer
17. SM = ScaleMode 'save current value
18. ScaleMode = 3 'pixel
19. PatternHeight = 32 'hard-coded value
20. PatternWidth = 32 'hard-coded value
21. For X = 0 To ScaleWidth Step PatternWidth
22. For Y = 0 To ScaleHeight Step PatternHeight
23. D = BitBlt(hDC, X, Y, PatternWidth, PatternHeight, hDC, 0, 0, SRCCOPY)
24. Next Y
25. Next X
Abstract
When you are designing an application, Visual Basic® lets you assign the MousePointer
property of many controls to one of the twelve predefined mouse cursors. Typically you
would change the MousePointer property of a control to tell your program's user that
some kind of action has been invoked. For example, the hourglass cursor is used to
indicate the passage of time. At other times, you may just want to inform the user that she
or he positioned the mouse pointer over a specific control, such as a File List Box. To do
this, you would simply change the MousePointer property of that control at the
appropriate time in your Visual Basic application.
However, you may want to display a cursor shape not included in the twelve predefined
shapes. This article explains how you can create a different mouse pointer (cursor), even
for controls that do not have a MousePointer property.
Example Program
The following program changes the mouse pointer to a different shape when the pointer
is moved over a File List Box control.
3. Set the DragIcon property of the File1 control to an .ICO file of your choice.
Abstract
Visual Basic® offers many functions that can be used to manipulate text strings. Using
the LCase and UCase functions, you can change the characters in a string to all
lowercase or all uppercase letters. This article shows how you can convert the first letter
of each word in a string to a capital letter.
Example Program
The following Visual Basic program converts the sentence in the first text box so that
each word is capitalized.
1. Start a new project in Visual Basic. Form1 is created by default.
2. Add a Text Box control to Form1. Text1 is created by default. Set its MultiLine
property to True.
3. Add a second Text Box control to Form1. Text2 is created by default. Set its
MultiLine property to True.
Abstract
In a Visual Basic® application, you have several methods available to display printed
text to your user. For example, you can use the Text property of a Text Box. However,
the text you display in the Text Box is limited to a specific color. This article shows how
text can be displayed with any number of color combinations.
Therefore, by using the Line method to draw text on a form, which in turn causes a Paint
event to be triggered, you can display text in whatever color you desire.
The Line method is used to draw lines, boxes, and filled boxes on the printer, the Picture
Box, and the form controls. To draw a line, you specify the starting position, the ending
position, and an optional color to be used. The CurrentX and CurrentY properties can be
used to set or retrieve the current print position within the control where printing takes
place.
When drawing text to a control, you must first calculate the space required to draw the
character. You do this using the TextWidth and TextHeight methods. Once you have
drawn the character on the control with the Line method, you can then use the ForeColor
property to change the color of the drawn character.
Example Program
The following Visual Basic program displays the letters A–Z in different colors on the
program's form.
Abstract
You can use two Windows® application programming interface (API) functions to
determine the exact size and position of a window within your Visual Basic®
application: The GetWindowRect function returns the screen coordinates of the
window's normal position, and the GetWindowPlacement function reports the window's
position both when minimized or maximized, in addition to the window's normal
position. This article explains how you can use these two functions in a Visual Basic
application.
To declare this function within your program, include the following Declare statement in
the Global Module or General Declarations section of your application's form:
Declare Sub GetWindowRect Lib "User" (ByVal hWnd As Integer, lpRect As RECT)
Note that this Declare statement must be typed as one single line of text.
The GetWindowRect function can be called by passing it two arguments. The hWnd
argument must contain the handle of the window that you want to retrieve information
for. After calling GetWindowRect, the function stores the window information in the
Example Program
The program below uses the GetWindowRect function to display the window's size in
the first text box and the GetWindowPlacement function to display the window's left,
right, top, and bottom coordinates.
1. Start a new project in Visual Basic. Form1 is created by default.
2. Add a Text Box control to Form1. Text1 is created by default. Set its MultiLine
property to True.
3. Add a second Text Box control to Form1. Text2 is created by default. Set its
MultiLine property to True.
26. Add the following Declare statements and structures to Module1.Bas (note that
each Declare statement must be typed as a single line of text):
27. Declare Sub GetWindowRect Lib "User" (ByVal hWnd As Integer, lpRect As RECT)
28. Declare Sub GetWindowPlacement Lib "User" (ByVal hWnd As Integer, lpWnd
29. As WINDOWPLACEMENT)
30. Type RECT '8 bytes
31. Left As Integer
32. Top As Integer
33. Right As Integer
34. Bottom As Integer
35. End Type
36. Type POINTAPI '4 bytes
37. X As Integer
38. Y As Integer
39. End Type
40. Type WINDOWPLACEMENT '22 bytes
41. Length As Integer
42. Flags As Integer
43. ShowCmd As Integer
44. PtMinPosition As POINTAPI
45. PtMaxPosition As POINTAPI
46. RcNormalPosition As RECT
47. End Type
Abstract
From within a Visual Basic® application, you can terminate another Windows®-based
application that is currently running. To do this, you send a WM_CLOSE command to
the running application. This terminates the program just as if you had clicked on the
Close command in the application's control menu. This article explains how you can
terminate a program from within a Visual Basic application.
The Windows API PostMessage function is the key to terminating a program running in
Windows. After you have determined the application's handle, you simply execute the
PostMessage function with the WM_CLOSE command as an argument.
To declare this function within your program, include the following Declare statement in
the Global Module or General Declarations section of your form:
Declare Function PostMessage Lib "User" (ByVal Hwnd As Integer, ByVal wMsg
As Integer, ByVal wParam As Integer, ByVal lParam As Long) As Integer
Note that this Declare statement must be typed as one single line of text.
The PostMessage function requires four arguments to be passed to it. These arguments
are as follows:
hWnd An integer value set to the window's handle
wMsg An integer value set to the message ID that you want to send to the window
wParam An integer value set to a 16-bit parameter (depends on wMsg)
lParam A string or long value (depends on wMsg)
After calling the PostMessage function, an integer value will be returned. If this value is
set to TRUE (nonzero), the function was successful and the target application was
terminated.
Example Program
The following Visual Basic program shows how you can terminate an application
currently running in Windows. This example assumes that the application you want to
terminate is the Windows Solitaire game and that it is currently running in memory.
When you execute this program, it will display a message box telling you either that
Solitaire is not running (in which case the program simply ends) or that Solitaire is
running. Click the OK command button and Solitaire will be immediately terminated.
1. Start a new project in Visual Basic. Form1 is created by default.
2. Add the following Constants and Declare statements to the General Declarations
section of Form1 (note that each Declare statement must be typed as a single line
of text):
3. Declare Function IsWindow Lib "User" (ByVal Hwnd As Integer) As Integer
Abstract
In your Visual Basic® application, you may want to restrict the movement of the mouse
pointer (cursor) to a certain control or area of a window. This technique is called
clipping, and can be accomplished by calling the Windows® application programming
interface (API) ClipCursorRect and SetCursorPos functions.
The ClipCursorRect function can be called by passing it just one argument—a RECT
rectangle structure. This structure describes the area to which you want to restrict the
cursor's movement. The RECT structure is defined as follows:
Type RECT
Left As Integer
Top As Integer
Right As Integer
Bottom As Integer
End Type
The left, right, top, and bottom values represent the area's coordinates within the window
that you want to work with. After you have determined the area you want to restrict
cursor movement to, you must use the SetCursorPos function to move the cursor to this
area. As stated earlier, you would add the Declare statement for this function to the
General Declarations section as:
Example Program
The following program shows how you can restrict the mouse pointer's movement within
a Visual Basic program. In this example, you can only move the mouse pointer with the
Text Box control as long as the time delay is in effect. After the For-Next loop has
finished its work, the mouse pointer's movement is restored to its normal functionality.
22. Add the following Declare statements to the General Declarations section of
Form1 (note that each Declare statement must be typed as one single line of text):
23. Declare Sub ClipCursorRect Lib "User" Alias "ClipCursor" (lpRect As RECT)
24. Declare Sub SetCursorPos Lib "User" (ByVal X As Integer, ByVal Y As Integer)
25. Declare Sub ClipCursorClear Lib "User" Alias "ClipCursor" (ByVal lpRect As Long)
26. Add a new BAS module to the project. Module1.Bas is created by default.
Abstract
When developing a Visual Basic® application that will be executed on different
computer systems, you may need to determine at run time how many colors are supported
by the target machine's display driver. This article explains how to do this using three
Windows® application programming interface (API) functions.
Because we want to know how many colors the display device supports, we call the
CreateDC function by issuing the statement:
hDC = CreateDC("DISPLAY", "", "", "")
The hDC variable will contain a handle to the device context just created. We can use this
handle to retrieve information about the device through the GetDeviceCaps function.
The Declare statement for the GetDeviceCaps function is:
Declare Function GetDeviceCaps Lib "GDI" (ByVal hDC As Integer, ByVal nIndex As Integer) As Integer
This function takes two arguments: the device's handle and a constant value that specifies
the type of information the function should retrieve. In our case, we need to call the
GetDeviceCaps function twice to retrieve the number of color planes and the number of
bits per pixel for each plane. From these two values, we can calculate how many colors
the display driver supports.
Calculating the number of colors supported by the display device is simple. You need to
multiply the number of bits per pixel by the number of color planes. However, since each
bit can represent two colors, the number of bits must first be raised to the power of 2.
This will give you the total number of colors the display device currently supports.
The last step you need to do is to call the DeleteDC function. The Declare statement for
the DeleteDC function is:
Declare Function DeleteDC Lib "GDI" (ByVal hDC As Integer) As Integer
You must call the DeleteDC function to remove the device context that you have created
earlier. This removes the device context and also frees the windows resources occupied
by the device context.
Example Program
The program below shows how you can determine the number of colors that a device
supports. This example calculates the number of colors supported by the display (screen)
device driver. The result is displayed in the text box.
3. Add the following Constants and Declare statements to the General Declarations
section of Form1 (note that each Declare statement must be typed as one single
line of text):
4. Declare Function GetDeviceCaps Lib "GDI" (ByVal hDC As Integer, ByVal nIndex
Abstract
You can use the Visual Basic® Line method to add special effects to your application's
appearance. This article explains how you can draw a double-line border around a form's
window.
Example Program
The following Visual Basic program draws a double-line border around a form's window
area.
Abstract
This article explains how you can use the Visual Basic® Dir$, FileName, and FileLen
functions to calculate the space used by files in a directory.
How, then, can you find out how much space is used by the files? One solution is to open
each file in the directory and move the files pointer to the end of the file. Then you can
• The FileLen function returns the total number of bytes used by the specified file.
Using a Do-While loop to retrieve the name and length of each file found in the
directory is quicker and less prone to disk errors than the other method described
above.
Example Program
The program below shows how you can use a Do-While loop to calculate how many
bytes are occupied by all the files stored in a directory. The Directory variable is set to
the path of the directory you want to work with. After the program has determined the
length of all files stored in the directory, it displays the result in the Text Box.
1. Create a new project in Visual Basic. Form1 is created by default.
Abstract
When creating a new Visual Basic® application, you can add much to the program's
appearance and ease of use if you include bitmap (.BMP) graphic files. Bitmap files are
simply pictures or images saved in a special format. These bitmaps are available from
many different sources, including commercial online services. This article explains how
you can create your own custom bitmap files.
Let's suppose that you want to design a bitmap that contains just the name of your Visual
Basic program. By setting a string variable to the application's name and using the
SavePicture statement, you can quickly create the desired bitmap file. The syntax for the
SavePicture statement is:
SavePicture Image, <filename>
where <filename> is the name of the bitmap file you want to create and Image is the
.BMP, .ICO, or .WMF graphic file format. In the example program below, we have
drawn the text on the Picture Box control; therefore, to save it to disk with the
SavePicture statement, we must also include the control's name in the command string.
Example Program
The following Visual Basic program uses the Print method to draw the text on the
Picture Box and then saves the resulting image to disk as a bitmap file.
2. Add a Picture Box control to Form1. Picture1 is created by default. Set its
AutoRedraw property to True.
Abstract
The ability to change the appearance of the default Windows® icon can add a great deal
of flexibility and user-friendliness to your Visual Basic® application. Visual Basic
provides twelve different cursor shapes to choose from. For example, the hourglass
cursor is generally used to tell the user of your application that some type of lengthy
operation is taking place. When that operation has been completed, the cursor reverts
back to its normal pointer shape. This article explains how you can create your own
custom cursor shapes.
• The AND bitmap is the second bitmap. Its image consists of an AND mask that is
combined with the XORed bitmap. Used in this way, the AND and XOR
operators create the icon's new image.
In Visual Basic, you can use the Windows® CreateCursor function to create a
completely new and different cursor shape. To use this function within your program,
The CreateCursor function returns an integer value that identifies the cursor. If this
value is zero, the function was unable to create the new cursor.
Once you have created the cursor, you need to tell Windows to use the new cursor by
calling the GetClassWord and SetClassWord functions. Call the GetClassWord
function first so that you can save the cursor's handle. Then you can restore the original
cursor's image or set the cursor's image to a new one by calling the SetClassWord
function.
The Declare statements for the GetClassWord and SetClassWord functions are:
Declare Function GetClassWord Lib "User" (ByVal hWnd As Integer, ByVal nIndex
As Integer) As Integer
Declare Function SetClassWord Lib "User" (ByVal hWnd As Integer, ByVal nIndex
As Integer, ByVal wNewWord As Integer) As Integer
Note that each Declare statement must be typed as one line of text.
To retrieve the default cursor's handle, you pass two arguments to the GetClassWord
function: the handle of the window that owns the cursor, and a value specifying the type
of information you want to retrieve. In this case, we would specify the GCW_HCURSOR
constant (the cursor's default handle). In our application, we save the returned handle to
an integer variable so that we can use it again later in the program.
The SetClassWord function takes an additional argument: the new value for the class
information. The class information, of course, refers to the cursor's new image.
Example Program
The following Visual Basic program displays a different cursor image on the screen. In
this example, the XORBitPlane and ANDBitPlane values are used to manipulate the
cursor's current image, thereby creating a new cursor. You can create your own custom
cursors in Visual Basic by modifying the original cursor as this example program does.
27. Add the following code to the Click event for Command2:
28. Sub Command2_Click()
29. X = SetClassWord(Form1.hWnd, -12, OldCursor)
30. Dummy% = DeleteObject(hCursor)
31. End Sub
Abstract
The Windows® operating system can be configured to run a screen saver after a specified
amount of time has elapsed without any keyboard or mouse activity being sensed.
However, in certain situations, you may need to deactivate the screen saver, do some
processing in your Visual Basic® application, and then reactivate the screen saver. This
article explains how to do this in a Visual Basic program.
To declare this function in your Visual Basic program, include the following Declare
statement in the Global Module or General Declarations section of your program:
For a list of the Windows settings you can modify, see the Knowledge Base article
Q97142, "How to Use SystemParametersInfo API for Control Panel Settings," referenced
at the end of this article.
This function returns an integer value. If this value is TRUE (nonzero), the changes were
made successfully. If the return value is FALSE (zero), the function was not able to make
the requested changes to the operating system.
Example Program
The following program demonstrates how the Windows screen saver can be temporarily
activated or deactivated. To turn the screen saver off, click the Deactivate command
button; to turn the screen saver on again, click the Activate command button.
2. Add the following constant and Declare statements to the general declarations
section of Form1 (note that the Declare statement must be typed as a single line
of text):
3. Declare Function SystemParametersInfo Lib "User" (ByVal uAction As Integer,
4. ByVal uParam As Integer, lpvParam As Any, ByVal fuWinIni As Integer)
5. As Integer
6.
7. Const SPI_SETSCREENSAVEACTIVE = 17
8. Add a Command Button control to Form1. Command1 is created by default. Set
its Caption property to "Activate".
15. Add the following code to the Click event for Command2:
16. Sub Command2_Click()
17. Dim ret As Integer
18. ret = SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, False, 0, 0)
19. End Sub
Abstract
Every time a new file is created, the operating system gives the file one or more special
attribute settings. In your Visual Basic® program, you can use the GetAttr and SetAttr
functions to modify a file's attribute settings.
You can determine which attributes a file has been given by using the Visual Basic®
GetAttr function. The syntax for this function is:
GetAttr(filename)
SetAttr(filename),(attribute)
When changing a file's attributes, you must keep in mind that a file can have more than
one attribute set at any given time. You must use the And operator to change only the
desired bit in the attribute flag. The following table tells you the mask values you can use
to change only the individual bit you are interested in.
Attribute Mask Value
Archive 31
System 59
Hidden 61
Read Only 62
You can also remove all the attributes of a file by calling SetAttr with a value of zero as
the Attribute value.
Example Program
The following program shows how you can use the GetAttr and SetAttr functions in a
Visual Basic application. Execute this program by pressing the F5 function key. Click the
"Test Archive Bit" command button. The program will respond by testing the
AUTOEXEC.BAT file's attribute flag to see if its Archive bit is set. If the Archive bit is
set, the program responds with the message, "File has archive bit set." Click the "Set
Archive Off" command button. This resets the file's Archive bit to zero; the resulting
message is displayed in the Text Box.
1. Create a new project in Visual Basic. Form1 is created by default.
14. Add the following code to the Click event for Command2:
15. Sub Command2_Click()
16. FileName = "c:\autoexec.bat"
17. SetAttr FileName, GetAttr(FileName) And 31
18. Text1.Text = "Archive attribute set to Off."
19. End Sub
20. Add a Text Box control to Form1. Text1 is created by default.
Abstract
The Windows® BitBlt function can be used to display a bitmap image on a Visual
Basic® form. The bitmap image can be an image stored in memory or an image stored on
disk. This article demonstrates how the BitBlt function can display a bitmap file on the
screen.
If you're trying to copy a bitmap and the source and destination contexts are not
compatible, you must first use the CreateDIBitmap function. This function takes a
device-independent bitmap and converts it to a device-dependent bitmap. To declare this
function within your program, include the following Declare statement in the General
Declarations section of your form:
Declare Function CreateDIBitmap Lib "GDI" (ByVal hDC As Integer, lpInfoHeader
As BITMAPINFOHEADER, ByVal dwUsage As Long, ByVal lpInitBits As String,
lpInitInfo As BITMAPINFO, ByVal wUsage As Integer) As Integer
Now you can call the BitBlt function to draw the bitmap image on the screen. This works
exactly as if you had used the LoadPicture method.
You should also use the DeleteDC and DeleteObject functions to release the Windows
resources used by the device context and bitmap you have just created.
Example Program
The following program shows how you can quickly draw a bitmap image on your Visual
Basic form. The TARTAN.BMP file shipped with Windows® is used in this example,
but any other bitmap that is 32 x 32 pixels can be substituted.
1. Create a new project in Visual Basic. Form1 is created by default. Set its
AutoRedraw property to True.
Abstract
Visual Basic® offers several commands to manipulate disk files. You can delete a file
with the Kill statement and delete a directory with the RmDir function. If the Visual
It's easy to see how the Kill and RmDir statements can be used to delete entire directory
structures very quickly. The example program below starts off by changing to the target
directory and then deleting all files stored in that directory. Once all the files from this
directory have been deleted, the program removes the empty directories it finds. This
process is repeated until the entire target directory and its associated files have been
successfully removed from the disk.
The example program only processes files that have a file attribute of Normal. This
means that you would have to modify the program to search for and delete files with
other attributes, such as hidden, read-only, or volume label files.
Example Program
The following program will delete all the files in a directory. Note that in this example it
is assumed that a directory named TEST exists on drive C. All files, including nested
subdirectories and their files, will be removed from disk with this program.
Abstract
When you execute an MS-DOS® program from within a Visual Basic® application, your
MS-DOS program uses the default MS-DOS icon. This article explains how, using some
functions from Windows®, you can change this default icon to a different icon of your
choice.
The next step is to use the SetClassWord function to retrieve the handle of the default
icon used by the specified window. After the Shell method has executed the TEST.BAT
file (in our demonstration program below), we use the SetClassWord function to
actually change the default icon to another icon.
You should note that we are changing the icon for the MS-DOS window to another icon,
and that this new icon will be used by all other applications within this same window
class (DOS). This is why, in the demonstration program below, we take the final step of
deleting the new MS-DOS icon just before the program is terminated.
Example Program
The following program shows how the default MS-DOS icon can be changed to a
different icon from within a Visual Basic application.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that each statement must be typed as a single line of text):
3. Const SWP_NOSIZE = 1
4. Const SWP_NOMOVE = 2
5. Const SWP_NOACTIVATE = &H10
6. Const SWP_SHOWWINDOW = &H40
7. Const SWP_HIDEWINDOW = &H80
8. Const SWP_FLAGS = SWP_NOMOVE Or SWP_NOSIZE Or SWP_NOACTIVATE
9. Const SWP_SHOW = SWP_SHOWWINDOW Or SWP_FLAGS
10. Const SWP_HIDE = SWP_HIDEWINDOW Or SWP_FLAGS
11. Const HWND_BOTTOM = 1
12. Const GCW_HICON = (-14)
13. Const GCW_HMODULE = (-16)
14.
15. Declare Function GetModuleUsage Lib "Kernel" (ByVal hWnd%) As Integer
16.
17. Declare Function ExtractIcon Lib "Shell" (ByVal hInst%, ByVal lpExeName$,
18. ByVal hIcon%) As Integer
19.
20. Declare Function DestroyIcon Lib "User" (ByVal hIcon%) As Integer
73. Save the project as DOSBOX.MAK. Select Make EXE File from Visual Basic's
File menu to create an executable program file called C:\DOSMAK.EXE.
Abstract
In a Visual Basic® application, you may want to save the contents of a window's client
area to the Windows® Clipboard application. You can save data to the Clipboard in a
variety of formats. This article explains how the client area of a window can be saved to
the Clipboard in Windows as a bitmap file.
Because we want to save the contents of a window to the Clipboard, we call the
SetClipboardData function by passing it the MF_BITMAP constant, which tells the
function to save the window's data in the Clipboard in bitmap file format.
Example Program
The following program shows how to copy the contents of a window's client area (the
entire window, in this case) to the Clipboard in bitmap format. After executing this
program, you can verify that the data was saved to the Clipboard by running Clipboard
Viewer from the Accessories group in Program Manager.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that each statement must be typed as a single line of text):
3. Declare Function BitBlt Lib "GDI" (ByVal hDestDC As Integer, ByVal X As Integer,
4. ByVal Y As Integer, ByVal nWidth As Integer, ByVal nHeight As Integer, ByVal
5. hSrcDC As Integer, ByVal XSrc As Integer, ByVal YSrc As Integer, ByVal dwRop
6. As Long) As Integer
7.
8. Declare Function GetWindowDC Lib "User" (ByVal hWnd As Integer) As Integer
9.
10. Declare Function CreateCompatibleDC Lib "GDI" (ByVal hDC As Integer) As Integer
11.
12. Declare Function CreateCompatibleBitmap Lib "GDI" (ByVal hDC As Integer, ByVal
13. nWidth As Integer, ByVal nHeight As Integer) As Integer
14.
15. Declare Function SelectObject Lib "GDI" (ByVal hDC As Integer, ByVal hObject As
16. Integer) As Integer
17.
18. Declare Function OpenClipboard Lib "User" (ByVal hWnd As Integer) As Integer
19.
Abstract
To make your Visual Basic® applications more visually attractive, you can center each
form on your screen. Centering forms can be done by using the Height and Width
properties of the form and then using the Move method to position the form at its new
location on the screen.
Example Program
The following program shows how you can center a form in your Visual Basic
application.
Abstract
Many Windows®-based applications allow you to "drag" an item from one location on
the screen to another and then "drop" the selected item in a new position. This technique
is called drag and drop. Items can be dragged from one control to another, or even
between two different Windows-based applications. This article explains how you can
use the drag-and-drop technique to move individual items to new positions within a list
box control.
Example Program
The following Visual Basic program lets you "drag and drop" an item in a List Box to
another position within the same List Box. This, in effect, allows you to selectively sort
the items in a List Box without using the Sorted property.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that the Declare statement must be typed as one single line
of text):
3. Declare Function SendMessage Lib "User" (ByVal hWnd As Integer, ByVal wMsg
4. As Integer, ByVal wParam As Integer, lParam As Any) As Long
5. Const LB_GETTOPINDEX = &H400 + 15
6. Add the following code to the Form_Load event for Form1:
7. Sub Form_Load()
8. Dim i As Integer
9. Me.Show
10. For i = 1 To 10
11. List1.AddItem "Item " & i
12. Next i
13. End Sub
14. Add a List Box control to Form1. List1 is created by default.
15. Add the following code to the MouseDown event for List1:
16. Sub List1_MouseDown(Button As Integer, Shift As Integer, X As Single,
17. Y As Single)
18. Static SecondClick As Integer
19. Static DropText As String
20. Dim RowHeight As Single
21. Dim TopI As Integer, InsertI As Single
22. TopI = SendMessage(List1.hWnd, LB_GETTOPINDEX, 0&, 0&)
23. RowHeight = TextHeight("X")
24. InsertI = Y \ RowHeight
25. If Button = 2 And DropText = "" And SecondClick = False Then
26. List1.ListIndex = InsertI + TopI
27. DropText = List1.Text
28. MousePointer = 10
29. SecondClick = True
30. List1.RemoveItem InsertI + TopI
31. ElseIf Button = 2 And Len(DropText) > 2 And SecondClick = True Then
32. If InsertI + TopI < List1.ListCount - 1 Then
33. List1.AddItem DropText, InsertI + TopI
34. Else
35. List1.AddItem DropText, InsertI + TopI + 1
36. End If
37. DropText = ""
Abstract
When a Visual Basic® program is executing a time-consuming task, you can display the
progress of that task by using a status bar in the program. This article explains how you
can use a three-dimensional control to add this feature to your Visual Basic programs.
Example Program
The following program shows how you can add a percentage-completed status bar to
your own Visual Basic application. It is assumed that you have a temporary file called
TEST.COM in the root directory of drive C. As this program reads data from the
temporary file, it displays the percentage completed on the status bar. The program ends
when the entire file has been processed, showing a "100 percent completed" message in
the status bar.
Abstract
Almost every Windows®-based application displays a caption in its title bar. This
caption is usually the application's name. This article will tell you how you can modify
the caption of an application.
After calling this function, GetWindowText will return an integer value set to the length
of the caption's text. This length count does not include the string's terminating NULL
character.
The Windows API SetWindowText function allows you to set the contents of the title
bar's caption to a string of your choice. The SetWindowText function requires two
arguments, as follows:
hWnd An integer value containing the window's handle.
lpString A string containing the window's new title bar caption.
The example program below retrieves the text stored in the title bar ("Caption Demo")
and adds the current time to the string. However, we must take a couple of steps to ensure
that Visual Basic displays the new caption correctly.
First, we use the Left$ function to remove the original caption's terminating NULL byte.
Later on in the program, we retrieve the current time as a string and append it to the end
of the original caption stored in the title bar. If we did not remove the terminating NULL
byte from the original caption's string, Visual Basic would stop printing the text before it
reached the time portion of the string.
Approximately every ten seconds, the Timer control is used to update the target
window's title bar. However, another step must be included in this routine to prevent
Windows from appending the time string more than once.
The example program below adds the current time to the window's title bar. The first
time the Timer executes its code, the original title bar's caption is "Caption Demo". The
second time the routine is executed, the original title bar's caption is "Caption Demo
08:12:11" (or whatever the current time happens to be). If we keep appending the current
time to the original title bar's caption, the string will soon contain multiple but different
time stamps. This is not what we want—we only want one time stamp to be included in
the string. This is why the example program searches for the first colon character in the
Example Program
The following program shows how to modify an application's title bar. This program
adds the current time to the caption of the target window—in this case, our own Visual
Basic program. After executing this program, Visual Basic will add the current time to
the caption of Form1. The entire string will be updated approximately every ten seconds.
1. Create a new project in Visual Basic. Form1 is created by default. Set its Caption
property to "Caption Demo".
2. Add a Timer control to Form1. Timer1 is created by default. Set its Interval
property to 10000.
Abstract
The Professional Edition of Visual Basic® provides controls to create three-dimensional
(3D) check boxes, command buttons, frame controls, group push buttons, option buttons,
and panels. This article explains how you can add this 3D-look to controls without using
the 3D controls provided in Visual Basic. The routine used in the example program will
work with both the Standard and Professional editions of Visual Basic.
Creating 3D Controls
You can change the appearance of a control such as a Text Box by giving it a three-
dimensional (3D) look. This effect can be achieved by using the Line method in Visual
Basic® to draw borders around the target control.
The example program below draws a raised border on two sides of the Text Box and
Label controls. This code can be easily modified to create more professional looking
Visual Basic applications.
Example Program
The program below shows how to add three-dimensional effects to a Text Box and Label
control. By modifying the BorderOffset, BorderWidth, and RaisedBorder variables, you
can change the appearance of the target control very quickly.
1. Create a new project in Visual Basic. Form1 is created by default. Set its
AutoRedraw property to True.
OriginalForeColor = TargetForm.ForeColor
OriginalDrawWidth = TargetForm.DrawWidth
If RaisedBorder Then
UpperColor = QBColor(15)
LowerColor = QBColor(8)
Else
UpperColor = QBColor(8)
LowerColor = QBColor(15)
End If
Abstract
In many Windows®-based applications, the user can resize a window by dragging one of
the window's borders to a new position. This article will tell you how to prevent a form
from being resized. You can also modify the example program so that it will allow the
user to resize the form only to a certain size.
To declare these two functions within your program, include the following Declare
statements in the Global Module or General Declarations section of your application's
form (note that each Declare statement must be typed as one single line of text):
Declare Sub GetWindowPlacement Lib "User" (ByVal hWnd As Integer, lpWnd
As WINDOWPLACEMENT)
After we call the GetWindowPlacement function, we can retrieve the window's current
size and save these values in variables for later use in our application.
Example Program
The example program below uses the GetWindowPlacement and
SetWindowPlacement functions to prevent the form from being resized. You can
optionally add code to allow the window to be resized only to a specific size, if desired.
1. Start a new project in Visual Basic. Form1 is created by default.
49. Add the following Declare statements and type structures to Module1.Bas (note
that each Declare statement should be typed as a single line of text):
50. Declare Sub GetWindowPlacement Lib "User" (ByVal hWnd As Integer, lpWnd
51. As WINDOWPLACEMENT)
52.
53. Declare Function SetWindowPlacement Lib "User" (ByVal hWnd As Integer, lpWndPl
54. As WINDOWPLACEMENT) As Integer
55.
56. Type RECT '8 bytes
57. Left As Integer
58. Top As Integer
59. Right As Integer
60. Bottom As Integer
61. End Type
62.
63. Type POINTAPI '4 bytes
64. X As Integer
65. Y As Integer
66. End Type
67.
68. Type WINDOWPLACEMENT '22 bytes
69. Length As Integer
70. Flags As Integer
71. ShowCmd As Integer
72. PtMinPosition As POINTAPI
73. PtMaxPosition As POINTAPI
74. RcNormalPosition As RECT
75. End Type
76. Run the program. Try to resize the form by clicking and dragging one of the
form's borders. The form will immediately reset to its previous size.
The Windows API FreeLibrary function unloads a previously loaded .DLL. The
FreeLibrary function should be called after you have tried to load a .DLL file with the
LoadLibrary function. This function's declaration statement is as follows:
Declare Sub FreeLibrary Lib "Kernel" (ByVal h As Integer)
To unload a .DLL from memory, you simply call the FreeLibrary function with the
module's instance handle.
If your Visual Basic application attempts to load a .DLL that does not exist, Windows
will respond with a critical-error-handler message box. You can use the Windows API
SetErrorMode function to tell Windows to handle the error or to tell Windows that your
program will process the error condition itself. The declaration statement for
SetErrorMode is as follows:
Declare Function SetErrorMode Lib "Kernel" (ByVal wMode As Integer) As Integer
This function requires only one argument: a constant value that tells Windows how to
handle Interrupt 24h errors. The value you pass to SetErrorMode may be a combination
of these values:
SEM_FAILCRITICALERRORSWindows does not display the critical-error-handler
message box and so returns the error to the calling
application.
SEM_NOGPFAULTERRORBOX Windows does not display the general-protection-
After calling the SetErrorMode function, an integer value is returned. This value is the
previous state of the error-mode flag.
In a Visual Basic application, you can use the SetErrorMode function in conjunction
with the LoadLibrary and FreeLibrary functions to determine if a user's system has the
.DLL files your program needs.
Example Program
The following program shows how to trap Error Code 48, "Error in loading DLL", from
within your Visual Basic application.
1. Create a new project in Visual Basic. Form1 is created by default.
24. Create a new function called DoesLibraryExist. Add the following code to this
function (note that the first line, the OriginalErrorValue% lines, and all Explain$
lines must be typed as a single line of code):
Abstract
There are various methods of sorting data in a Visual Basic® application. This article
explains how to sort an integer array while preserving the array's original sort order.
Example Program
1. Create a new project in Visual Basic. Form1 is created by default.
46. Add a second List Box control to Form1. List2 is created by default.
Abstract
This article explains how you can design an application in Visual Basic® that acts like a
virus. You can use this program to prevent unauthorized users from using your system for
more than 10 minutes.
Example Program
44. Add the following code to the Timer event for Timer1 (please note that the
MsgBox line must be typed as a single line of code):
45. Sub Timer1_Timer()
46. Const Max_Intervals = 5 '5 minutes
47. NumTimerEvents = NumTimerEvents + 1
48. If NumTimerEvents >= Max_Intervals Then
69. Add the MSDNBUG.EXE program to the StartUp group on your Windows
desktop.
Abstract
The List Box control provided in Visual Basic® allows you to create a list of items,
optionally sorted alphabetically. Each item can contain any type of ASCII characters,
including control codes such as the tab character, and all items can be sorted if the Sort
property of the List Box is set to True. However, when trying to add items separated by
tabs, the output is not correctly formatted in two or more columns. This article will
explain how you can correctly format items in a List Box that contain embedded tab
(ASCII 9) characters.
Example Program
The program below shows how to add items to a List Box control. Each item consists of
three parts, separated by tab characters.
1. Create a new project in Visual Basic®. Form1 is created by default.
35. Create a new Sub procedure called gSetListTabs. Add the following code to this
procedure (note that the Sub line must be typed as a single line of code):
36. Sub gSetListTabs(fForm As Form, iListHandle As Integer, iNumberOfColumns As
37. Integer, iListTabs() As Integer)
38.
39. '* 'fForm'-the form on which the listbox resides *
40. '* 'iListHandle'-listbox hWnd (I use GetFocus()) *
41. '* 'iNumberOfColumns'-# of tabs wanted in the listbox*
42. '* 'iListTabs()'-the array of tab positions you want *
43.
44. Dim iListDlgWidth As Integer, lTextWidth As Long
45.
46.
47. 'Get the Pixel width
48. Dim iPixelWidth As Integer
49. fForm.ScaleMode = PIXELS 'Set to Pixels(3)
50. iPixelWidth = fForm.ScaleWidth 'Get Scalewidth in pixels
51. fForm.ScaleMode = Twips 'Set back to Twips(1)
52.
53. 'Set the Twip to Pixel Ratio
54. Dim sinTwipPixelRatio As Single
55. sinTwipPixelRatio = 1 / (fForm.ScaleWidth / iPixelWidth)
56.
57. 'Get the screen device context
58. Dim iWindowContext As Integer
59. iWindowContext = GetDC(fForm.hWnd)
60.
61. 'Use the device context to get the horizontal resolution
62. Dim iHorzResPixels As Integer
63. iHorzResPixels = GetDeviceCaps(iWindowContext, HORZRES)
64.
65. 'Calculate the screen resolution ratio
66. Dim sinScreenRatio As Single
67. sinScreenRatio = (640 / iHorzResPixels)
68.
69. 'Set up and calc the 'textwidth' average
70. Dim sTemp As String, iTemp As Integer
71. sTemp = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"
72. iTemp = 62
73.
74. 'GetTextExtent() returns a long, the lower 16 bits have
75. 'the font textwidth in twips
76. lTextWidth = GetTextExtent(iWindowContext, sTemp, iTemp)
77. iListDlgWidth = (lTextWidth Mod 65536) / 2 'bottom 16 in Twips
78. iListDlgWidth = iListDlgWidth * sinTwipPixelRatio 'apply ratio
79. iListDlgWidth = CInt(iListDlgWidth * sinScreenRatio) / 15 'Res 640 x480
80. iListDlgWidth = 15
81.
82. 'Apply factor to each tab position
Abstract
When developing an application in Visual Basic®, you may need to determine what word
or phrase is under the mouse pointer. This article will demonstrate, through the use of an
example program, how to retrieve text from a control.
Example Program
The following program shows how to retrieve a word or phrase under the mouse pointer
(cursor).
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following code to the Form_Load event for Form1 (note that each Words
line must be typed as a single line of code):
3. Sub Form_Load()
4. 'Make the picture box take up the form's entire client area.
5. Form1.Picture1.Top = 0
40. Add the following code to the MouseMove event for Picture1 (note that the Sub
line must be typed as a single line of code):
41. Sub Picture1_MouseMove(Button As Integer, Shift As Integer, X As Single,
42. Y As Single)
43. Form1.Caption = ""
44. For I = 0 To UBound(Words)
45. If Y >= Words(I).Top And Y <= Words(I).Bottom Then
46. If X >= Words(I).Left And X <= Words(I).Right Then
47. Form1.Caption = Words(I).PromptText
48. End If
49. End If
50. Next
51. End Sub
52. Create a new Sub procedure called ParseText. Add the following code to this
procedure:
53. Sub ParseText(Text$, WordHolder() As WordType)
54. 'Find the number of spaces in the text, to determine
55. 'approx. how many words are in it.
Abstract
The Windows SDK Help File contains a description of each windows message you can
use with the SendMessage function. For now, the message we want to send to Program
Manager is represented by the value 107, which initiates the File/Run menu selection in
Program Manager. In the example program below, the SendMessage function executes
the File/Run command, then the DoEvents statement waits until that command has been
processed, and then control returns to the program, with Form1 set to have the focus.
Example Program
The following program executes the File/Run command from Program Manager. When
you run this program, click on the command button. The File/Run dialog box will be
called up on your screen. Select any Windows-based application you wish to run. After
that application has terminated, control returns to this program.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that each Declare statement must be typed as a single line
of code):
3. Declare Function FindWindow Lib "User" (ByVal lpClassName As String, ByVal
4. lpWindowName As Long) As Integer
5.
6. Declare Function SendMessage Lib "User" (ByVal hWnd As Integer, ByVal wMsg
7. As Integer, ByVal wParam As Integer, ByVal lParam As Long) As Long
8. Const WM_COMMAND = &H111
9. Add a Command Button control to Form1. Command1 is created by default. Set
its Caption property to "Execute File/Run".
10. Add the following code to the Click event for Command1:
11. Sub Command1_Click()
12. Dim RunFile As Integer
13. Dim Result As Integer
14.
15. RunFile = FindWindow("ProgMan", 0)
16. If RunFile <> 0 Then
17. Result = SendMessage(RunFile, WM_COMMAND, 107, 0)
18. DoEvents
19. Form1.SetFocus
20. End If
21.
22. End Sub
Abstract
When designing a Visual Basic® application, you may want to include code that allows
the user to resize, for example, two Text Boxes by dragging and dropping a splitter bar.
This article explains how to create a program that uses a splitter bar to enlarge or shrink
the two Text Boxes to different sizes.
Each Text Box control is responsible for calling the Resize event of the program's main
form, Form1. This Resize event causes Visual Basic to draw each Text Box control to its
new size at its new position. This same technique can be applied to almost any other form
or control except menus, timers, lines, and shapes.
Example Program
1. Create a new project in Visual Basic. Form1 is created by default. Set the
following properties for Form1:
Abstract
This article explains how you can use the Windows® application programming interface
(API) FindExecutable function to determine which filename extension is associated with
a specific Windows-based application.
After executing the FindExecutable function, an integer value will be returned indicating
success or failure. If the value returned is greater than 32, the function was successful and
lpszResult will contain the full path and filename of the executable application associated
with the file. If the value returned is less than 32, the function was not successful.
FindExecutable can return the following error codes:
0 Insufficient system memory or corrupt program file
2 File not found
3 Path not found
5 Sharing or protection error
6 Separate data segments required for each task
8 Insufficient memory to run application
10 Windows version is incorrect
11 Program file is invalid
12 Program requires a different operating system
13 Program requires MSDOS 4.0
14 Program type is unknown
15 Protected memory mode is not supported
16 When loading a second instance of a program, invalid use of data segments
19 Cannot execute a compressed program file
20 Not a valid dynamic-link library (DLL)
21 Windows 32-bit extensions is required
Example Program
Abstract
In a Visual Basic® application you can update the contents of a List Box control by
using the AddItem or RemoveItem methods. However, if you do not want the contents
of the modified List Box to be updated until all items have been added or deleted, you
can use the Windows® application programming interface (API) SendMessage function
to set a flag (WM_SETREDRAW) telling Windows not to update the control until you
specifically ask it to do so. This article explains how you can prevent a List Box control
from being updated immediately.
Setting the redraw flag to TRUE turns the redraw function on, and setting the redraw flag
to FALSE turns the redraw function off. Therefore, in a Visual Basic application that is
updating a List Box, you must send the WM_SETREDRAW message before you actually
begin manipulating the contents of the control. After you have finished adding or
removing items from the List Box control, you can send another WM_SETREDRAW
message to turn the redraw function on again. This will cause Windows to display the
modified List Box control immediately.
Example Program
The program shown below displays two List Box controls on the form. You can select
items from the first List Box by clicking them. Each selected item will be added to the
second List Box control when you click the "Show Results" command button.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that each Declare statement should be typed as a single
line of code):
3. Const WM_SetRedraw = &HB
4. Const LB_ADDSTRING = &H401
5.
6. Declare Function SendMessage Lib "User" (ByVal hWnd As Integer, ByVal wMsg As
7. Integer, ByVal wParam As Integer, lParam As Any) As Integer
8.
9. Declare Function SendMessageByString Lib "User" Alias "PostMessage" (ByVal hWnd
10. As Integer, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As
11. String) As Integer
23. Add the following code to the Click event for Command1:
24. Sub Command1_Click()
25. 'Show updated list box now
26. X = SendMessage(List2.hWnd, WM_SetRedraw, 1, 0)
27. End Sub
28. Add a List Box control to Form1. List1 is created by default. Set its MultiSelect
property to True.
29. Add the following code to the DblClick event for List1:
30. Sub List1_DblClick()
31. 'Disable the Repaint event
32. X = SendMessage(List2.hWnd, WM_SetRedraw, 0, 0)
33.
34. S = List1.List(List1.ListIndex)
35. ' Must use SendMessageByString instead of
36. ' List2.AddItem S to prevent redrawing
37. D = SendMessageByString(List2.hWnd, LB_ADDSTRING, 0, S)
38. End Sub
39. Add a second List Box control to Form1. List2 is created by default.
Abstract
This article explains how you can force a Visual Basic® Text Box control to convert all
typed text to either uppercase or lowercase characters.
After the GetWindowLong function is executed, a long value is returned. This value
depends on the specific nIndex argument used to call the function.
To change a window's style, you call the SetWindowLong function. Its Declare
statement is as follows (note that it must be typed as a single line of code):
Declare Function SetWindowLong Lib "User" (ByVal hWnd As Integer, ByVal nIndex
As Integer, ByVal dwNewLong As Long) As Long
The SetWindowLong function requires one more argument than the GetWindowLong
function, namely, dwNewLong. This long value should contain the new style value you
want to apply to the specified window.
When you want to force a Text Box control to convert typed text to uppercase characters,
you can call SetWindowLong with dwNewLong set to the constant ES_UPPERCASE.
Conversely, to convert all typed text to lowercase characters, you call SetWindowLong
with dwNewLong set to the constant ES_LOWERCASE. In an actual Visual Basic
application, you would first preserve the control's original window style and then restore
the window's style when your special task has been completed.
10. Add the following code to the Click event for Command1:
11. Sub Command1_Click()
12. Text1.Text = ""
13. X = ChangeCase(Text1, True)
14. Text1.SetFocus
15. End Sub
16. Add a second Command Button control to Form1. Command2 is created by
default. Set its Caption property to "Lowercase Only".
17. Add the following code to the Click event for Command2:
18. Sub Command2_Click()
19. Text1.Text = ""
20. X = ChangeCase(Text1, False)
21. Text1.SetFocus
22. End Sub
23. Create a new function called ChangeCase. Add the following code to this
function:
24. Function ChangeCase(TheControl As Control, UpLow As Integer) As Integer
25. Const GWL_STYLE = (-16)
26. Const ES_UPPERCASE = &H8&
27. Const ES_LOWERCASE = &H10&
28. Dim Rtn As Long
29. Dim EditStyle As Long
30. EditStyle = GetWindowLong(TheControl.hWnd, GWL_STYLE)
31. If UpLow = True Then
32. EditStyle = EditStyle Or ES_UPPERCASE
Abstract
When developing an application in Visual Basic®, you may need to ask the user to enter
a fully qualified path, such as when saving a data file to disk. However, your program
may need to determine if the specified directory and filename are valid DOS names, or
you may need to use the individual elements of the path in some other way. This article
demonstrates how you can write a procedure to extract the individual path, filename, and
filename extension from a fully qualified path.
Example Program
The following program shows how you can separate a fully qualified path into separate
directory, filename, and filename extension fields.
2. Add a Text Box control to Form1. Text1 is created by default. Set its MultiLine
property to True.
Abstract
When developing an application in Visual Basic®, you may need to perform a task that
should not be interrupted. This article explains how to use the Windows® application
programming interface (API) SetSysModalWindow and LockInput functions to disable
task-switching.
When your program is terminated, you must use the LockInput function to restore input
to other Windows-based programs. In addition, you must destroy the system modal
Example Program
The program below shows how you can prevent a user from switching to another
Windows-based application while your program is executing.
1. Create a new project in Visual Basic. Form1 is created by default.
33. Add the following code to the Click event for Command1:
34. Sub Command1_Click()
35. X = LockInput(0, TopHwnd, 0)
Abstract
You can add online Help to your Visual Basic® application by using the Windows®
application programming interface (API) WinHelp function. However, you need to keep
the focus on the control that had the focus just before you executed the WinHelp
function. This article explains how a control can retain the focus after calling WinHelp.
After the user exits the Help program, however, the Command Button control now has
the focus. It would be preferable to have the focus set to the control (such as a Text Box
control) that had the focus before WinHelp was executed.
You can force your application to automatically retain a control's focus by defining a
Form-level variable as a control. When the focus is moved to a different control, such as
a Text Box, the Form-level variable should be set to the control that is getting the focus.
Then, after displaying the Help file, the focus can be set back to the control by using the
Form-level variable.
In the example program below, the focus returns to the Text Box control each time the
Help Command Button is clicked. In other words, the Command Button never retains the
focus.
Example Program
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following statements to the General Declarations section of Form1 (note
that the Declare statement should be typed as a single line of code):
3. Const HELP_CONTENTS = &H3
4.
5. Declare Function WinHelp Lib "User" (ByVal hWnd As Integer, ByVal lpHelpFile As
6. String, ByVal wCommand As Integer, dwData As Any) As Integer
10. Add the following code to the GotFocus event for Text1:
11. Sub Text1_GotFocus()
12. Set ControlWithFocus = Text1
13. End Sub
14. Add a second Text Box control to Form1. Text2 is created by default.
15. Add the following code to the GotFocus event for Text2:
16. Sub Text2_GotFocus()
17. Set ControlWithFocus = Text2
18. End Sub
19. Add a Command Button control to Form1. Command1 is created by default. Set
its Caption property to "Help".
20. Add the following code to the Click event for Command1:
21. Sub Command1_Click()
22. Dim RVal As Integer
23. RVal = WinHelp(Form1.hWnd, "c:\vb\vb.hlp", HELP_CONTENTS, 0)
24. ControlWithFocus.SetFocus
25. End Sub
Run the program. There are two Text Box controls and one Command Button control
shown on the form. Notice that Text1 currently has the focus. Click the Command Button
to display the Contents window in Help. Exit Help. The Text1 control should still have
the focus. Move the focus to the second Text Box control, Text2. Click the Help
command button a second time and exit Help. The second Text Box control should have
the focus. The Command Button control never retains the focus.
Abstract
The Visual Basic® StrComp function can be used in conjunction with the RemoveItem
method to delete entries that are duplicated in List Box controls. This article explains
If you have two List Box controls in your Visual Basic application and you want to
remove the items from the second control that are already in the first List Box, you can
use the StrComp function, which allows you to compare two strings to see if they are
identical.
When using StrComp to determine if two strings are identical, you can tell the function
to ignore uppercase and lowercase differences. In other words, the function can be told to
treat the string "this is a test" to be the same as or different from the string "THIS IS A
TEST".
If you want StrComp to ignore the case of the strings you are comparing, use the 1
argument. To make StrComp include the case of the strings in the comparison, use the 0
argument (that is, X = StrComp(String1, String2, 0) or X=StrComp(String1, String2, 1).) In
addition, the Option Compare Text command, which you would place in the General
Declarations section of a form or module, tells StrComp (and other string functions) that
all string comparisons are to ignore the upper- and lowercase differences.
After you call the StrComp function, it returns the status of the string comparison.
StrComp returns one of the following four possible values.
-1 The first string is less than the second string.
0 The first string is identical to the second string.
1 The first string is greater than the second string.
NULL Either String1 or String2 is a NULL (empty) string.
Example Program
The program below shows how to remove duplicate items from List Box controls. When
the program is first executed, both List Box controls contain two entries that are
identical. Clicking the "Remove Duplicates" command button removes the identical
items from the second List Box control.
1. Create a new project in Visual Basic. Form1 is created by default.
15. Add a second List Box control to Form1. List2 is created by default. Set its
Sorted property to True.
17. Add the following code to the Click event for Command1:
18. Sub Command1_Click()
19. Call EliminateDupEntries(List1, List2)
20. End Sub
21. Create a new function called EliminateDupEntries. Add the following code to
this function:
22. Sub EliminateDupEntries(First As Control, Sec As Control)
23. Dim Findx As Integer
24. Dim Sindx As Integer
25. Dim Ret As Integer
26.
27. Findx = 0
28. For Sindx = 0 To Sec.ListCount - 1
29. For Findx = Sindx To First.ListCount - 1
30. Ret = StrComp(First.List(Findx), Sec.List(Sindx))
31. Select Case Ret
32. Case 0:
33. Sec.RemoveItem Sindx
34. Sindx = Sindx - 1
35. Exit For
36. Case 1:
37. Exit For
38. End Select
39. Next Findx
40. Next Sindx
41. End Sub
Abstract
When developing an application in Visual Basic® that may be run on many different
computer systems, you may want to ensure that a control such as a Picture Box is
formatted correctly with regard to the size and type of font used. This article explains
how you can use the Windows® application programming interface (API) SendMessage
and GetStockObject functions to force a control to use a specific font when displaying
text.
In the example program below, we want to force the Picture Box control to use a fixed
font instead of Bookman Old Style, which is set to a point size of 24, at design time. To
set the font to a fixed font while the program is being executed, we issue the following
statement:
X = SendMessage(Picture1.hWnd, WM_SETFONT, GetStockObject(ANSI_FIXED_FONT), 1)
After issuing this command, anytime we use the Print method to print text on the Picture
Box control, the fixed font is used.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that each Declare statement should be typed as a single
line of code):
3. Declare Function SendMessage Lib "User" (ByVal hWnd As Integer, ByVal wMsg As
4. Integer, ByVal wParam As Integer, lParam As Any) As Long
5. Declare Function GetStockObject Lib "GDI" (ByVal nIndex As Integer) As Integer
6. Const ANSI_FIXED_FONT = 11
7. Const WM_SETFONT = &H30
8. Add the following code to the Form_Load event for Form1:
9. Sub Form_Load()
10. Dim X As Long
11. X = SendMessage(Picture1.hWnd, WM_SETFONT, GetStockObject(ANSI_FIXED_FONT),
12. 1)
13. Picture1.Print "This is a test"
14.
15. End Sub
16. Add a Picture Box control to Form1. Set its Font property to Bookman Old
Style, point size: 24.
Abstract
When developing an application in Visual Basic®, you may need to create a temporary
file on disk. This article explains how to use the Windows® application programming
interface (API) GetTempFileName function to create temporary files.
The GetTempFileName function will create the temporary file on the first hard disk or
on the disk specified by the TEMP environment variable. You can set the
TF_FORCEDRIVE bit of the cDriveLetter argument to tell the GetTempFileName
function to create the file in the current directory of the specified disk. In all other cases,
the temporary file will be created on the disk specified in the cDriveLetter argument.
After you call the GetTempFileName function, the file will have been created on the
specified disk. The lpTempFileName buffer will contain the file's complete path,
terminated by the number specified by the wUnique argument.
Once you have successfully created the temporary file from within your application, you
can isolate the actual filename by issuing these two statements:
TempFileName = Left(TempFileName, InStr(TempFileName, Chr(0)) - 1)
TempFileName = Trim(Right(TempFileName, Len(TempFileName) - 3))
The first statement uses the InStr function to strip off the last character returned in the
buffer used to hold the filename. This byte is the value used in the wUnique argument.
The second statement removes the preceding "C:\" drive specifier characters from the
filename.
You should be aware that temporary files created by the GetTempFileName function
remain on the disk until you actually delete them.
Example Program
The following program shows how you can create temporary files from within your
Visual Basic application. Each time you execute this program, a new temporary file is
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that the Declare statement must be typed as a single line
of code):
3. Declare Function GetTempFileName Lib "Kernel" (ByVal cDriveLetter As Integer,
4. ByVal lpPrefixString As String, ByVal wUnique As Integer, ByVal
5. lpTempFileName As String) As Integer
6. Const TF_FORCEDRIVE = &H80
7. Add the following code to the Form_Load event for Form1:
8. Sub Form_Load()
9. Dim X As Integer
10. Dim Drive As Integer
11. Dim Prefix As String
12. Dim Unique As Integer
13. Dim TempFileName As String
14. Dim PathName As String
15.
16. TempFileName = Space$(144)
17. NewFileName = Space$(144)
18.
19. PathName = "C:\WINDOWS"
20. Drive = Asc(UCase(Left(PathName, 1))) + TF_FORCEDRIVE
21. Prefix = "DATA"
22. Unique = 0
23.
24. ChDir PathName
25. X = GetTempFileName(Drive, Prefix, Unique, TempFileName)
26. TempFileName = Left(TempFileName, InStr(TempFileName, Chr(0)) - 1)
27. TempFileName = Trim(Right(TempFileName, Len(TempFileName) - 3))
28. Text1.Text = TempFileName
29. End Sub
30. Add a Text Box control to Form1. Text1 is created by default.
Abstract
When an object, such as a form, is moved at run time, Windows generates a MOVE
message. By trapping the MouseDown event for a control, you can tell Visual Basic to
issue a move command to the operating system. This system command (MOVE) tells
Windows to move the window to the new position.
In the example program below, the user can move both the form and command button to
new locations. When the MouseDown event is triggered for the control, the
ReleaseCapture function is called. Next, the SendMessage function tells Windows to
actually execute the MOVE command. This anchors the object at its new position on the
screen.
Example Program
The example program below shows how to drag a control, such as a form or command
button, to a new position on the screen.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that each Declare statement must be typed as a single line
of code):
3. Const WM_SYSCOMMAND = &H112
4. Const SC_MOVE = &HF012
5. Declare Sub ReleaseCapture Lib "User" ()
6. Declare Sub SendMessage Lib "User" (ByVal hWnd As Integer, ByVal wMsg
7. As Integer, ByVal wParam As Integer, lParam As Long)
15. Add the following code to the MouseDown event for Command1:
16. Sub Command1_MouseDown(Button As Integer, Shift As Integer, X As Single,
17. Y As Single)
18. ReleaseCapture
19. SendMessage Command1.hWnd, WM_SYSCOMMAND, SC_MOVE, 0
20. End Sub
Abstract
The Default property of a Command Button can be used to place the focus on the
control at run time. If this property is set to True, the Command Button receives the
focus; if it is set to False, the Command Button does not have the focus. In addition, the
SetFocus method can be used to shift the focus to a specific control or form. However,
the mouse pointer's position is not changed. This article explains how you can position
the mouse pointer over the control that has just received the focus.
How do we actually determine the position of a control on the screen? First, we know
that the Command Button control has both Width and Height properties that tell us the
exact size of the control; ditto for the Form control. To calculate the approximate
Example Program
The program below shows how to move the mouse pointer to the control that has just
received the focus.
1. Create a new project in Visual Basic. Form1 is created by default.
Run the program a second time. Using the mouse, click the No Command Button. The
Command Button receives the focus and the mouse pointer is positioned over the
button. This demonstrates that no matter which one is used to move the focus—the TAB
key or the mouse—the mouse pointer can be programmed to follow control that has the
focus.
Abstract
You can use the Visual Basic® MkDir statement to create a new directory on any floppy
or hard disk. This article explains how you can use this statement to create nested
subdirectories, even if part of the path already exists.
MkDir "C:\<JUNK>"
where JUNK is the name of the directory you want to create and C:\ is the drive you want
to create it on. If you want to create a nested subdirectory, for example C:\JUNK\TEST,
you must first create the JUNK directory and then create the TEST directory. However, if
The example program below creates a directory that is three levels deep, called
"\JUNK\TEST\TEST". The first time the MkDir statement is executed, it creates the
JUNK directory. The second and third times MkDir is executed, however, it produces
Error 76. The Resume Next statement tells our program to ignore this error each time it
is encountered until we have successfully created the entire directory structure.
Example Program
This program shows how to create nested directories even if one of the directories in the
path already exists.
Abstract
You can add code to your Visual Basic® application to allow a user to scroll through the
contents of two separate List Box controls at the same time. This article explains how
you can add this functionality to your program.
Let's assume that you have two List Box controls on a form in your Visual Basic®
application. As you scroll through the items in the first List Box control, you want to also
scroll through the same items in the second List Box control.
We first use a static variable—that is, a variable whose contents do not change when we
exit a procedure—to keep track of the currently selected item in the first List Box. Each
time a new item is selected in the List Box, this variable is set to that item's TopIndex
value.
Next, we set the ListIndex property of the second List Box control equal to that of the
first List Box control. This highlights the two items in each List Box that have the same
ListIndex value. It doesn't matter what the actual item is—the items are both selected
based on their position within the controls.
Each time you select an item in the first List Box, that same item is also selected in the
second List Box.
Example Program
This example program shows how to scroll through the contents of two List Box controls
simultaneously.
1. Create a new project in Visual Basic. Form1 is created by default.
20. Add a second List Box control to Form1. List2 is created by default.
22. Add the following code to the Click event for Command1:
23. Private Sub Command1_Click()
24. End
25. End Sub
26. Add a Timer control to Form1. Timer1 is created by default.
27. Add the following code to the Timer1 event for Timer1:
28. Private Sub timer1_Timer()
29. Static PrevList1
30. Dim TopIndex_List1 As Integer
31.
32. 'Get the index for the first item in the visible list.
33. TopIndex_List1 = List1.TopIndex
34.
35. 'See if top index has changed.
36. If TopIndex_List1 <> PrevList1 Then
37. 'Set the top index of List2 equal to List1,
38. 'so that the list boxes scroll together.
39. List2.TopIndex = TopIndex_List1
40. PrevList1 = TopIndex_List1
41. End If
42. 'Select the item in the same position in both list boxes.
43. If List1.ListIndex <> List2.ListIndex Then
44. List2.ListIndex = List1.ListIndex
45. End If
46.
47. End Sub
Abstract
Within a Visual Basic® application, you can execute a menu item in another Windows®-
based program. This article explains how to use several Windows application
programming interface (API) functions to execute menu commands.
• You also need to retrieve the handle associated with the target window's menu.
The GetMenu function will return the handle as an integer value.
• Once you have the target window's menu handle, you need to determine the
entry's position in the menu and retrieve the handle of the pop-up menu. In the
example program below, we want to retrieve the handle of the File menu
selection. Therefore, we would call the GetSubMenu function with zero as the
entry's position. The first entry in every pop-up menu always begins with entry
number zero.
• Next, we want to retrieve the ID number of the specific menu entry we want to
execute. We retrieve this ID number by calling the GetMenuItemID function
with the entry's position specified as one (the position of the Open menu selection
in the pop-up menu).
• The final step is to make the target application the active application and to issue
the SendMessage function, which in turn sends a WM_COMMAND message to
the target window. The WM_COMMAND message is set to the target
application's window to execute the File/Open command.
Example Program
The following example program executes another application's menu commands. This
program assumes that the Windows Notepad application program is already running in
memory. This program uses SendMessage to execute the File/Open menu selection in
Notepad.
When you execute the program, click the Command Button. After a second or two, you
will see that Notepad has been activated and that its Open File dialog box is displayed on
the screen.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that each Declare statement should be typed as a single
line of code):
3. Private Declare Function FindWindow Lib "User" (ByVal lpClassName As Any, ByVal
4. lpWindowName As Any) As Integer
5. Private Declare Function GetMenu Lib "User" (ByVal hWnd As Integer) As Integer
6. Private Declare Function GetMenuItemID Lib "User" (ByVal hMenu As Integer, ByVal
7. nPos As Integer) As Integer
8. Private Declare Function GetSubMenu Lib "User" (ByVal hMenu As Integer, ByVal
9. nPos As Integer) As Integer
14. Add the following code to the Click event for Command1:
15. Private Sub Command1_Click()
16. Dim hWnd As Integer
17. Dim hMainMenu As Integer
18. Dim hMenu As Integer
19. Dim MenuID As Integer
20.
21. hWnd = FindWindow("NotePad", "Untitled - NotePad")
22. If hWnd = 0 Then Exit Sub
23.
24. hMainMenu = GetMenu(hWnd)
25. hMenu = GetSubMenu(hMainMenu, 0)
26. MenuID = GetMenuItemID(hMenu, 1)
27. AppActivate "Untitled - NotePad"
28. X& = SendMessage(hWnd, WM_COMMAND, MenuID, 0&)
29.
30. End Sub
Abstract
When using a List Box control in a Visual Basic® application, the user can click on an
item with the left mouse button. That item then becomes selected. This article explains
how you can select items with the right mouse button instead of the left mouse button.
Example Program
The example program below displays a List Box control on a form. Whenever you click
the right mouse button on an item in the List Box, the message "Right Click on" is
displayed in the Text Box along with the index number corresponding to the selected
item.
9. Add the following code to the MouseUp event for List1 (note that the Private
lines must be typed as a single line of code):
10. Private Sub List1_MouseUp(Button As Integer, Shift As Integer, X As Single,
11. Y As Single)
12. Dim Item%
13. If (Button = 2) Then
14. Item% = GetRClickedItem(List1, X, Y)
15. If (Item% = LB_ERR) Then
16. Text1.Text = "ERROR"
17. Else
18. Text1.Text = "Right Click on " + Str(Item%)
19. End If
20. End If
21. End Sub
22. Add a Text Box control to Form1. Text1 is created by default.
24. Add the following code to the Module.Bas file (note that the Private and If lines
must be typed as a single line of code):
25. Type RECT
26. Left As Integer
27. Top As Integer
28. Right As Integer
29. Bottom As Integer
30. End Type
31. Global Const WM_USER = &H400
32. Global Const LB_GETITEMRECT = (WM_USER + 25)
Abstract
You can use the Windows® application programming interface (API) MemManInfo
function to determine how much random access memory (RAM) is installed in the
computer system. This article explains how to retrieve the amount of RAM.
Example Program
Abstract
Calling the GetProfileString function returns an integer value. This value is a count of
the number of characters that were stored in the lpReturnedString buffer, but does not
include the terminating NULL byte. (Each entry returned in lpReturnedString is
terminated by a NULL character.) When your program is retrieving more than a single
entry, the last entry in the buffer is marked with two consecutive NULL bytes to signal
the end of the list.
Because we want to retrieve the names of all printers stored in the devices section of the
WIN.INI file, we would execute the following statement:
RetVal = GetProfileString(Section, 0&, "", Buffer, Len(Buffer))
This tells the GetProfileString function to retrieve all entries stored in the "devices"
section of WIN.INI (notice the 0& argument to tell the function to provide us with a list
of the entries).
Example Program
The example program below populates a List Box control with the names of all printers
attached to the computer system.
Abstract
This article explains how you can simultaneously close all child windows of a running
Visual Basic® application.
Example Program
The following program shows how to close all child forms at one time. Run the program
by pressing the F5 function key. The MDIForm1 form is displayed. Double-click the
client area of MDIForm1 to create a child form (Form1). Do this until you have several
child forms visible on the screen. Click the "Close Children" menu option to close all
child windows.
1. Create a new project in Visual Basic. Form1 is created by default. Set the
MDIChild property to True.
2. From Visual Basic's Insert menu, click "MDI Form" to create a Multiple
Document Interface form. MDIForm1 is created by default.
Abstract
You can draw borders of any width around controls such as Text Boxes to give the
control a three-dimensional look. This article explains how to add a border to a control.
After you have created a pen and brush to use with the specific object (such as a Text
Box control) that you want to draw filled lines around, you need to determine the
coordinates of the bounding rectangle around the target object. Next, you must intercept
the Windows WM_PAINT message. The WM_PAINT message triggers Visual Basic's
Paint event. The message is sent to a window when the window needs to have its client
area redrawn. The Message Blaster custom control can be used to process the
WM_PAINT message. For information on the Message Blaster custom control, see the
reference materials listed at the end of this article. Once the Paint event has been
triggered, the control is redrawn with the desired borders around its perimeter.
Example Program
The program below shows how to add a three-dimensional look to a Text Box control.
This program draws a filled line across the top and down the right-hand border of the
Text Box.
1. Create a new project in Visual Basic. Form1 is created by default.
3. From Visual Basic's Tools menu, select Custom Controls and add the
MSGBLAST.VBX to your Toolbox. Add a Message Blaster control to Form1.
MsgBlaster1 is created by default.
Abstract
Within a Visual Basic® application, you can compress and repair a Microsoft® Access®
database (.MDB) file. This article explains how you can accomplish these two tasks in
Visual Basic.
When records are deleted from a database file, the file can become defragmented. You
can compress a defragmented database file by using Visual Basic's CompactDatabase
statement. CompactDatabase's main purpose is to compress a Microsoft Access file, but
it can also be used to change the database's sort order, encrypt/decrypt the database, or
create a Microsoft Access 1.0 compatible file.
The CompactDatabase statement requires four arguments, as follows:
SourceFile The database's complete path and filename.
DestFile The database's new path and filename.
Locale The sorting order to be used.
Options Set to one of the following values:
DB_ENCRYPT Encrypt database.
DB_DECRYPT Decrypt database.
DB_VERSION10 Create a compatible Access 1.0 database file.
When the CompactDatabase statement is executed, it copies each valid record from the
original database file to the new database file. Note that these two filenames must be
different and that the security settings of the original file are automatically transferred to
the new file.
Example Program
The program below shows how to repair and/or compact a Microsoft Access database
(.MDB) file. To repair a damaged database file, click the "Repair" command button; to
compress (remove deleted records) a database file, click the "Compact" command button.
29. Add the following code to the Click event for Command2:
30. Private Sub Command2_Click()
31. On Error GoTo Compact_Error
32.
33. Dim MDB_Name As String
34. Dim MDB_NewName As String
35. Dim MDB_Local As String
36. Dim MDB_Options As String
37.
38. MDB_NewName = "c:\dummy.mdb"
39. CommonDialog1.Filter = "Access (*.MDB)|*.mdb"
40. CommonDialog1.Flags = &H1000
41. CommonDialog1.FilterIndex = 1
42. CommonDialog1.Action = 1
43.
44. If CommonDialog1.FileName <> "" Then
45. MDB_Name = CommonDialog1.FileName
46. CompactDatabase MDB_Name, MDB_NewName & MDB_Local & MDB_Options
47. Kill MDB_Name
48. Name MDB_NewName & MDB_Local & MDB_Options As MDB_Name
49. MsgBox "Database compressed OK", 64, "Compact"
50. End If
51. Exit Sub
52. Compact_Error:
53. MsgBox "Unable to compress database", 16, "Error"
54. Exit Sub
55. End Sub
Abstract
The Common Dialog control in Visual Basic® allows you to display an Open File dialog
box. You can select one or more filenames from the Open File dialog box to use within
your Visual Basic program. This article explains how you can retrieve multiple filenames
from the dialog box, parse them into separate strings, and display them in a List Box
control.
Example Program
1. Create a new project in Visual Basic. Form1 is created by default.
Abstract
This article describes a sample user-defined Access Basic function that you can use to
retrieve all field names and their associated properties for an attached Microsoft®
Access® table.
Example Program
This program demonstrates how to create and use the sample ListFieldProperties()
function.
1. Open the sample database NWIND.MDB. (This database can usually be found in
the C:\ACCESS\SAMPAPPS directory.)
17. In the Immediate window, type the following line and press the ENTER key:
18. ? ListFieldProperties()
The name of each field in the Categories table will be displayed along with that
field's properties.
The example program below shows how to use the BitBlt function to print scrolling text
on a Picture Box control. A Timer control is used to print a string of text on the Picture
Box control at selected time intervals.
Example Program
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following code to the General Declarations section of Form1 (note that
the Declare statement must be typed as a single line of code):
3. Const SRCCOPY = &HCC0020
4. Const ShowText$ = "This line of text scrolls vertically."
5. Private Declare Function BitBlt Lib "GDI" (ByVal hDestDC As Integer, ByVal X
6. As Integer, ByVal Y As Integer, ByVal nWidth As Integer, ByVal nHeight
7. As Integer, ByVal hSrcDC As Integer, ByVal XSrc As Integer, ByVal YSrc
8. As Integer, ByVal dwRop As Long) As Integer
9. Dim ShowIt%
10. Add a Picture Box control to Form1. Picture1 is created by default. Set its
ScaleMode property to 3-Pixel.
11. Add a Timer control to Form1. Timer1 is created by default. Set its Interval
property to 25.
12. Add the following code to the Timer event for Timer1 (note that the Ret = line
must be typed as a single line of code):
13. Private Sub Timer1_Timer()
14. Dim Ret As Integer
15. If (ShowIt% = 30) Then
16. Picture1.CurrentX = 0
17. Picture1.CurrentY = Picture1.ScaleHeight - 30
18. Picture1.Print ShowText$
19. ShowIt% = 0
20. Else
21. Ret = BitBlt(Picture1.hDC, 0, 0, Picture1.ScaleWidth,
22. Picture1.ScaleHeight - 1, Picture1.hDC, 0, 1, SRCCOPY)
23. ShowIt% = ShowIt% + 1
Abstract
There may be situations in which you do not want a multiple-document interface (MDI)
child form displayed while your program is executing. This article explains how you can
hide an MDI child form.
So how can you temporarily hide an MDI child window from the user? By moving the
window to a nonexistent position on your screen.
In the example program below, the MDI child form is moved off the current viewing area
of the screen. Windows® itself doesn't care where you place the window; and, to your
user, it appears as if the window has been hidden.
Example Program
This program shows how you can temporarily hide an MDI child form in your Visual
Basic® application. Run the program by pressing the F5 function key. The MDI child
window is visible on the screen. Click the mouse on the main form. The MDI child
window disappears from view. Double-click the main form and the MDI child form is
again visible on the screen.
1. Create a new project in Visual Basic. Form1 is created by default. Set the
following properties for Form1:
BorderStyle = 1-Fixed Single
Height = 1140
Left = 2220
3. From the Insert menu, select Form. Form2 is created by default. Set the form's
MDIChild property to True.
Abstract
Many Windows®-based applications can accept, or process, a file that has been dragged
from File Manager. This article explains how you can add this feature to your own Visual
Basic® application.
After calling the DragQueryFile function, an integer value reports the status of the
function. This value contains the number of characters copied to the lpszFile string or the
number of files available if Index was set to zero.
The third function needed to work with drag-and-drop files is the DragFinish function.
This function simply requires that the internal data structure's handle be passed to it.
DragFinish frees all structures used when transferring the file to the target application.
The final step is to process the WM_DROPFILES message. This message is sent by
Windows each time it needs to send a drag-and-drop request to a program. In your Visual
Basic program you need only use the Message Blaster custom control to intercept the
WM_DROPFILES message before Windows actually processes it itself. In the example
program below, we use the Message Blaster control to retrieve the name of the dropped
file and store that name in the List Box control.
2. Add the following code to the General Declarations section of Form1 (note that
each Declare statement must be typed as a single line of code):
3. Option Explicit
4. Private Declare Sub DragAcceptFiles Lib "shell" (ByVal hWnd As Integer, ByVal
5. bool As Integer)
6. Private Declare Function DragQueryFile Lib "shell" (ByVal wParam As Integer,
7. ByVal Index As Integer, ByVal lpszFile As Any, ByVal BufferSize As Integer)
8. As Integer
9. Private Declare Sub DragFinish Lib "shell" (ByVal hDrop As Integer)
10. Const WM_DROPFILES = &H233
11. Add the following code to the Form_Load event for Form1:
12. Private Sub Form_Load()
13. msgblaster1.MsgList(0) = WM_DROPFILES
14. msgblaster1.hWndTarget = Me.hWnd
15. msgblaster1.MsgPassage(0) = 1
16. DragAcceptFiles Me.hWnd, True
17.
18. End Sub
19. Add a Message Blaster custom control to Form1. MsgBlaster1 is created by
default.
20. Add the following code to the MsgBlaster1_Message event for MsgBlaster1:
21. Private Sub MsgBlaster1_Message(MsgVal As Integer, wParam As Integer, lParam As
22. Long, ReturnVal As Long)
23. Dim hFilesInfo As Integer
24. Dim szFileName As String
25. hFilesInfo = wParam
26. wTotalFiles = DragQueryFile(hFilesInfo, &HFFFF, ByVal 0&, 0)
27. For wIndex = 0 To wTotalFiles
28. szFileName = Space$(50)
29. Retv% = DragQueryFile(hFilesInfo, wIndex, szFileName, 50)
30. list1.AddItem szFileName
31. Next wIndex
32. DragFinish (hFilesInfo)
33. End Sub
34. Compile the program. From Visual Basic's File menu, select Make EXE File to
create the executable file called DEMO.EXE.
Abstract
You can use the Visual Basic® Print method to send text to the default printer. This
article explains how you can send data to the printer in any order (that is, you can print a
line of text in the middle of the page and then print some other text at the top of page).
Therefore, as the example program below shows, you can print to any specific physical
location on the paper. You can print a line of text in the center of the paper first and then,
by simply changing the CurrentX and CurrentY properties, print a line of text at the top
of the page.
Example Program
The example program below prints two lines of text on the default printer. The first line
is actually the second line to be physically transferred to the printer.
1. Create a new project in Visual Basic. Form1 is created by default.
Abstract
You can use the Windows® application programming interface (API) BitBlt function to
modify the size of an icon. This article explains how to enlarge or shrink an icon.
Example Program
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that the Declare statement must be typed as a single line
of code):
3. Private Declare Function BitBlt Lib "GDI" (ByVal hDestDC As Integer, ByVal X As
4. Integer, ByVal Y As Integer, ByVal nWidth As Integer, ByVal nHeight As
5. Integer, ByVal hSrcDC As Integer, ByVal XSrc As Integer, ByVal YSrc As
6. Integer, ByVal dwRop As Long) As Integer
7. Const SRCCOPY = &HCC0020
8. Add a Command Button control to Form1. Command1 is created by default. Set
its Caption property to "Shrink Icon".
34. Add a Picture Box control to Form1. Picture1 is created by default. Set its
AutoRedraw property to True.
Abstract
From within a Visual Basic® application, you can instruct Microsoft® Word to display
its Page Setup dialog box. This article explains how this task can be accomplished by
creating a Word Basic macro and executing that macro from within Visual Basic.
The next step is to call the Word Basic macro that you have previously created in Word.
In your Visual Basic program, you execute a Word Basic command with the
Object.Method syntax. For example, after executing Word, we want to start with a new
document. Therefore, we issue the statement wobjApp.FileNewDefault, where the
object has been defined as Word and FileNewDefault is the Basic command we want to
execute. A list of these Word Basic commands can be found in the WRDBASIC.HLP file
that is stored in the Word directory when you initially installed Microsoft Word.
After the new document screen has been displayed in Word, we want to actually execute
the Word Basic macro called CallFPS. To do this, we again issue a Word Basic
command called ToolsMacro. This command executes the specified macro file in Word.
When the macro has been terminated, we can close Word and return to our Visual Basic
program by issuing the Set wobjApp=Nothing statement. This statement removes the
object variable, which in turn causes Word to terminate.
Example Program
The following example program shows how you can invoke a Word Basic macro to call
up the Word Page Setup dialog box.
First, you must create the Word Basic macro that the Visual Basic program will call. Start
Word. From the Tools menu, select Macro. Type the name of the macro as FPSdlg and
click the Create command button.
Type the following as the macro's text. When you're done, save the macro so that it can
be used by all newly created Word documents.
Sub Main
Dim FPSdlg as FilePageSetup
GetCurValues FPSdlg
rc = Dialog(FPSdlg)
If rc <> 0 then
FilePageSetup FPSdlg
End If
End Sub
At this point, make sure the macro actually works from within Word. From the Tools
menu, select Macro. Click the name of the macro you want to execute—in this case, the
FPSdlg macro. Click the Run command button. Word should respond by popping up the
Page Setup dialog box. Click the Cancel button to return to the document screen. Exit
Word.
Now, you need to create the demonstration program in Visual Basic by following these
steps:
Abstract
Many Windows®-based applications have a toolbox from which you can select a
command to execute. When you move the cursor (mouse pointer) over an item in the
toolbox, a ToolTip is displayed. This article shows how to add this ToolTip help feature
to your own Visual Basic® applications.
Example Program
This program shows how to add ToolTips to a Visual Basic application. Press the F5
function key to run the example program. You will see a Command Button control and
a Text Box control on the form. Move the cursor over the Command Button and the
ToolTip message "A command button control to click on" will be displayed. Move the
cursor over the Text Box control and the ToolTip message "A text box control" will be
displayed.
1. Create a new project in Visual Basic. Form1 is created by default.
18. Add the following code to the Click event for Text1:
19. Private Sub Text1_Click()
20. ToolTips Me, Text1, False
21. End Sub
22. Add the following code to the MouseMove event for Text1 (note that the Private
line must be typed as a single line of code):
23. Private Sub Text1_MouseMove(Button As Integer, Shift As Integer, X As Single,
24. Y As Single)
25. ToolTips Me, Text1, True
26. End Sub
27. Create a new function called ToolTips. Add the following code to this function:
28. Sub ToolTips(Frm As Form, Ctl As Control, OnOff As Integer)
29. If OnOff Then
30. Frm.ToolTip.Cls
31. Frm.ToolTip.Print " " & Ctl.Tag & " "
32. Frm.ToolTip.Width = Frm.ToolTip.TextWidth(Ctl.Tag & " ")
Abstract
A Visual Basic® application may contain many different forms. This article presents a
function that can be used to determine if a form is currently loaded into memory.
Example Program
This program shows how to find out if a specific form is already loaded in a running
Visual Basic application.
1. Create a new project in Visual Basic. Form1 is created by default.
Abstract
From within a Visual Basic® application, you can execute an MS-DOS® program. This
article explains how to use the Shell statement in conjunction with the Windows®
application programming interface (API) GetNumTasks function to execute an MS-DOS
program.
While the MS-DOS program is executing, you can use the SendKeys statement to send
specific keystrokes to the application. In this manner, you can actually control what the
MS-DOS program does or provide some required input.
In addition, you can determine when the secondary program has terminated by using the
GetNumTasks function. To use the GetNumTasks function in your Visual Basic
application, you must include the following Declare statement in the Global Module or
General Declarations section of your form:
Private Declare Function GetNumTasks Lib "Kernel" () As Integer
The GetNumTasks function does not require any arguments but simply returns an
integer value set to the number of tasks that are currently running under Windows.
Therefore, to determine when your MS-DOS program has finished executing, call
GetNumTasks first, saving the value it returns in a variable. After the MS-DOS program
has finished executing, call the GetNumTasks function a second time to find out if the
number of tasks has decreased by a value of one. If the value has decreased, you know
that your MS-DOS program has finished executing and you can return control to your
Visual Basic application.
Example Program
This program shows how you can use the Shell function and the GetNumTasks function
to execute an MS-DOS program. This program assumes that you have the PKUNZIP
Abstract
The Windows® initialization file, WIN.INI, contains a list of all printers attached to the
computer system. This article contains an example program that retrieves the name of
each printer stored in the WIN.INI initialization file.
Example Program
This program retrieves the names of all installed printers from the WIN.INI initialization
file. The printer names are displayed in a List Box control.
2. Add the following Constant, Declare, and Type statements to the General
Declarations section of Form1 (note that each Declare statement must be typed as
a single line of text):
3. Option Explicit
4. Private Type WindowsDevice
5. WindowsDeviceUserName As String
6. WindowsDeviceShortName As String
7. WindowsDevicePortName As String
8. End Type
9. Private Declare Function GetProfileString Lib "Kernel" (ByVal lpAppName
10. As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal
11. lpReturnedString As String, ByVal nSize As Integer) As Integer
12. Private Declare Function GetPrivateProfileString Lib "Kernel" (ByVal lpAppName
13. As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal
14. lpReturnedString As String, ByVal nSize As Integer, ByVal lpFileName As
15. String) As Integer
16. Private Declare Function GetProfileKeys Lib "Kernel" Alias "GetProfileString"
17. (ByVal lpAppName As String, ByVal lpKeyName As Long, ByVal lpDefault As
18. String, ByVal lpReturnedString As String, ByVal nSize As Integer) As Integer
19. Private Declare Function GetPrivateProfileKeys Lib "Kernel" Alias
20. "GetPrivateProfileString" (ByVal lpAppName As String, ByVal lpKeyName As
21. Long, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal
22. nSize As Integer, ByVal lpFileName As String) As Integer
23. Const WINDOWS_SECTION_NAME = "windows"
24. Const DEVICES_SECTION_NAME = "devices"
25. Const DEVICE_KEY_NAME = "device"
26. Const NO_PRINTER = "(none)"
27. Add a Text Box control to Form1. Text1 is created by default.
29. Add the following code to the Click event for Command1 (note that the
List1.AddItem statement must be typed as a single line of code):
30. Private Sub Command1_Click()
31. Dim OrgPrinter As WindowsDevice
32. Call GetDefaultPrinter(OrgPrinter)
33. Text1.Text = OrgPrinter.WindowsDeviceUserName
34.
Abstract
The drag-and-drop functionality provided in many Windows®-based applications allows
you to copy an item from one program to another or from one control to another control
in the same application. This article explains how to use this drag-and-drop technique in
Visual Basic® to copy multiple items selected in a List Box control to another List Box
control.
Example Program
This program shows how to drag several items selected in one List Box control to
another List Box control. Run the example program by pressing the F5 function key.
From the first List Box control, click the mouse on several items to select (highlight)
them. While clicking each item, hold down the SHIFT key. When you want to drag the
selected items to the second List Box control, click once on the first List Box control and
hold the mouse button down while you drag the control to the second List Box. Release
the mouse button to drop the selected items onto the second List Box control.
19. Add the following code to the MouseDown event for List1 (note that the Private
line must be typed as a single line of code):
20. Private Sub List1_MouseDown(Button As Integer, Shift As Integer, X As Single,
21. Y As Single)
22. LGlobal = List1.ListIndex
23. For X = 1 To IG
24. List1.Selected(LIG(X)) = True
25. Next X
26. List1.Drag
27. End Sub
28. Add a second List Box control to Form1. List2 is created by default. Set its
MultiSelect property to 1-Simple.
29. Add the following code to the DragDrop event for List2:
30. Private Sub List2_DragDrop(Source As Control, X As Single, Y As Single)
31. For X = 0 To List1.ListCount - 1
32. If X = LGlobal Then
33. List2.AddItem List1.List(X)
34. Else
Abstract
A Microsoft® Access® database may contain several tables, with each table holding
many records. This article explains how to delete all records from all tables associated
with a Microsoft Access database application.
You can create an Access Basic function that will remove every record from the specified
table. However, if your Microsoft Access database contains many tables, you need to
process each individual table associated with that specific Microsoft Access database.
Example Program
This example Access program shows how to delete all records from every table in a
Microsoft Access database application. Note that this function also processes those table
names that include space characters in them (Inventory Year1, for example).
1. Open the sample database ORDERS.MDB. (This database can usually be found
in the C:\ACCESS\SAMPAPPS directory.)
Note: The example program will permanently modify this Access database.
Therefore, you should copy ORDERS.MDB to another directory and run this
program on the temporary copy of ORDERS.MDB.
19. In the Immediate Window, type the following line and press the ENTER key:
20. ?DeleteAllRecords()
This statement will execute the DeleteAllRecords() function. After a short time,
all records will be deleted from each table included in the ORDERS.MDB
database.
Abstract
You can position a form so it appears centered within another form. This article explains
how to center a form within its parent form. This same technique can be applied to
centering controls such as Picture Box controls over other controls.
In the same manner, you can center a form vertically within another form by using the
Top and Height properties of each form, dividing by two, and setting Form2's Top
property to the result.
Example Program
This program shows how to center a form over another form. After you run this example
program by pressing the F5 function key, click the Command Button. The program
displays Form2 centered over its "parent," Form1.
1. Create a new project in Visual Basic. Form1 is created by default.
Abstract
This article explains how you can determine what modules are currently running under
Microsoft® Windows® and create a task list based on that information.
Before you can use these two functions, however, you must initialize the dwSize field of
the MODULEENTRY structure. This value should be specified as the number of bytes
needed to store the information returned by ModuleFirst and ModuleNext.
Example Program
This program shows how to retrieve the module name and path for every running task
under Windows. The name of each module is displayed in the first List Box control,
while the full path of the module is displayed in the second List Box control.
2. Add the following code to the General Declarations section of Form1 (note that
each Declare statement should be typed as a single line of text):
3. Private Declare Function ModuleFirst Lib "toolhelp.dll" (mdlentry As
4. ModuleEntry) As Integer
5. Private Declare Function ModuleNext Lib "toolhelp.dll" (mdlentry As ModuleEntry)
6. As Integer
7. Add a Command Button control to Form1. Add the following code to the Click
event for Command1:
8. Private Sub Command1_Click()
9. Dim Tmp As ModuleEntry
10. Dim Retn As Integer
11.
12. Tmp.dwSize = Len(Tmp)
13. Retn = ModuleFirst(Tmp)
14.
15. While Retn <> 0
16. If InStr(Tmp.szExepath, ".VBX") <> 0 Or InStr(Tmp.szExepath, ".DLL") <>
17. 0 Or InStr(Tmp.szExepath, ">DRV") <> 0 Then
18. List1.AddItem Tmp.szModule
19. List2.AddItem Tmp.szExepath
20. End If
21. Tmp.szExepath = ""
22. Retn = ModuleNext(Tmp)
23. Wend
24. End Sub
25. Add a List Box control to Form1. List1 is created by default.
26. Add a second List Box control to Form1. List2 is created by default.
27. From the Insert menu, select Module. Module1.Bas is created by default.
Abstract
You may need to create a bitmap (.BMP) image file that contains a window's client area.
This article explains how to save a window's client area to disk in a bitmap image file
format.
Example Program
This program shows how to save the client area of a form or window and save it as a
.BMP file.
1. Create a new project in Visual Basic®. Form1 is created by default.
15. From the Insert menu, select Module to create a BASIC module. Module1.Bas is
created by default.
24. Add a Picture Box control to Form1. Picture1 is created by default. Set its
AutoRedraw property to True.
26. Add the following code to the Click event for Command1:
27. Private Sub Command1_Click()
28. SaveToPicture
29. End Sub
30. Create a new function called SaveToPicture. Add the following code to this
function:
31. Sub SaveToPicture()
32. Dim hDCCur As Long
33. Dim hWndCur As Long
34. Dim HWndOld As Long
35. Dim Tim As Double
36. Dim ThisRect As RECT
37. Dim DX As Long
Abstract
As the example program below shows, the CTL3D.DLL functions can enable your Visual
Basic application to display 3-D forms, message boxes, and common dialog boxes.
Example Program
1. Create a new project in Visual Basic. Form1 is created by default.
13. Add the following code to Module1.Bas (note that the Private lines must each be
typed as a single line of code):
14. Const SWW_HPARENT = -8
15. Const GWW_HINSTANCE = -6
16. Const GWW_HPARENT = -8
17. Const BUTTON_FACE = &H8000000F
18. Const FIXED_DOUBLE = 3
19. Const DS_MODALFRAME = &H80&
20. Const GWL_STYLE = (-16)
21. Private Declare Function Ctl3DSubClassDlgEx Lib "CTL3D.DLL" (ByVal hWnd As
22. Integer, ByVal Flags As Long) As Integer
Abstract
This article explains how you can print a Visual Basic® form several times on a single
piece of paper.
The technique presented in this article is useful for duplicating a form several times. For
example, if you designed a form to keep track of telephone messages, you could print
four messages per printed page, instead of using one piece of paper per telephone
message.
The StretchBlt function can be used to copy an image from one device context to
another. To use this function in your Visual Basic® application, include the following
In the example program below, the StretchBlt function is called four times to copy the
original Form1 to the destination Form2. Each time the copy operation is performed, the
destination is offset to the next quarter section of Form2.
Example Program
Before running this program, make sure your printer is online and ready to accept data.
Press the F5 function key to run the example program, which will print Form2 on the
paper four times.
1. Create a new project in Visual Basic. Form1 is created by default.
3. Add the following code to the Click event for Command1 (note that the X = lines
must each be typed as a single line of code):
4. Private Sub Command1_Click()
5. Dim W As Integer
6. Dim H As Integer
7. Dim X As Integer
8.
9. W = Form2.ScaleWidth / 2
10. H = Form2.ScaleHeight / 2
11. X = SetStretchBltMode(Form2.hDC, 3)
12. X = StretchBlt(Form2.hDC, 0, 0, W, H, Form1.hDC, 0, 0, Form1.ScaleWidth,
13. Form1.ScaleHeight, SRCCOPY)
14. X = StretchBlt(Form2.hDC, W, 0, W, H, Form1.hDC, 0, 0, Form1.ScaleWidth,
24. Add the following code to the General Declarations section of Form1 (note that
each Declare statement should be typed as a single line of code):
25. Private Declare Function SetStretchBltMode Lib "GDI" (ByVal hDC%, ByVal
26. nStretchMode%) As Integer
27. Private Declare Function StretchBlt Lib "GDI" (ByVal hDC%, ByVal X%, ByVal y%,
28. ByVal nWidth%, ByVal nHeight%, ByVal hSrcDC%, ByVal XSrc%, ByVal YSrc%, ByVal
29. nSrcWidth%, ByVal nSrcHeight%, ByVal dwRop&) As Integer
30. Const SRCCOPY = &HCC0020
Abstract
There are several icons built into the Windows® operating system that are used by
Windows when displaying message boxes. This article explains how to use the built-in
icons in your own Visual Basic® applications.
Example Program
This program shows how to use the built-in icons used by the Windows operating system.
This program displays the exclamation icon in the Picture Box control.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that each Declare statement must be typed as a single line
of code):
3. Private Declare Function DrawIcon Lib "User" (ByVal hDC As Integer, ByVal X
4. As Integer, ByVal y As Integer, ByVal hIcon As Integer) As Integer
5. Private Declare Function LoadIcon Lib "User" (ByVal hInstance As Integer, ByVal
6. lpIconName As Any) As Integer
7. Private Declare Function GetWindowDC Lib "User" (ByVal hWnd As Integer) As
8. Integer
9. Private Declare Function ReleaseDC Lib "User" (ByVal hWnd As Integer, ByVal hDC
10. As Integer) As Integer
11. Const IDI_EXCLAMATION = 32515&
12. Add a Picture Box control to Form1. Picture1 is created by default. Set its
AutoRedraw property to True.
14. Add the following code to the Click event for Command1:
15. Private Sub Command1_Click()
16. Dim hDCCur As Long
17. Dim hIcon As Integer
18. Dim X As Integer
Abstract
This article explains how you can modify the caption displayed in a multiple-document
interface (MDI) child window.
Example Program
This program shows how to modify a child window's caption text. Start this program by
pressing F5. The original caption is "MDIForm1 - [Form1]".
Start this program again after removing the Exit Sub statement from the Resize event (at
the beginning of the code listing). The caption for the MDIForm1 window now reads,
"MDIForm1 - Form1". The dash and bracket characters have been removed from the
2. From the Visual Basic Insert menu, select MDI Form. MDIForm1 is created by
default.
3. Set Form1's MDIChild property to True. Modify the size of this form so that it is
smaller than the MDIForm1 form.
Abstract
A multiple-document interface (MDI) window can contain multiple child windows. A
user can switch between child windows by pressing the CTRL+TAB or CTRL+F6 key
combinations. This article explains how you can prevent the user from using these keys
to switch to another child window.
When users want to switch from one child window to another, they press either
CTRL+TAB or CTRL+F6. The next window in the list is then brought to the top of the
window list (that is, it becomes the currently active window).
Example Program
This program shows how to disable the CTRL+F6 and CTRL+TAB key combinations so
that the user cannot move to the next MDI child window. Run the example program by
pressing F5. The program displays two child windows (Form1 and Form2) within an
MDI document window. Normally, you can press the CTRL+TAB or CTRL+F6 keys to
switch between the child windows. The Message Blaster control has been used to disable
these two key combinations if you try to use them in Form1. Click Form2 to bring that
child window to the top. Unlike Form 1, the Form 2 child window will process the
CTRL+TAB and CTRL+F6 key combinations.
1. Create a new project in Visual Basic. Form1 is created by default.
2. From the Visual Basic Insert menu, select MDI Form. MDIForm1 is created by
default.
4. From the Visual Basic Insert menu, select Form. Form2 is created by default.
6. From the Visual Basic Tools menu, select Custom Controls. Add a Message
Blaster control to Form1. MsgBlaster1 is created by default.
Abstract
Many Microsoft® Windows®-based applications include a Toolbox control. A toolbox is
a group of icons that the user can click to perform various operations within a running
application. These toolbox windows usually display a very small, thin title bar instead of
the normal-sized title bar. This article explains how you can create forms with thin title
bars in your Visual Basic® applications.
In the example program below, we use a Label control, sized to fit at the top of our form.
This control, which will become the thin title bar, responds to both the Click and
MouseDown events. These two events allow the user to click on the Label control (that
is, the thin title bar) and drag the entire form to a new location on the screen. This gives
our Microsoft® Visual Basic® application the same functionality as a toolbox window.
To enable our user to drag the form to a new location on the screen, we need to determine
the cursor's current X and Y coordinates on the screen. You can use the Microsoft®
Windows® application programming interface (API) GetCursorPos function to retrieve
the cursor's current location.
To call the GetCursorPos function, you must first add its Declare statement to the
General Declarations section of your Visual Basic application. Following is the
declaration for the GetCursorPos function:
Private Declare Sub GetCursorPos Lib "User" (lpPoint As POINTAPI)
The GetCursorPos function requires only one argument—a POINTAPI structure. This
structure will hold the cursor's current position, which is reported in screen coordinate
values.
The cursor's horizontal position is stored in the X variable; the cursor's vertical position is
stored in the Y variable within the POINTAPI structure:
Type POINTAPI
Example Program
This program shows how to create a form with a small title bar.
1. Create a new project in Visual Basic. Form1 is created by default.
3. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that the Declare statements must be typed as single lines
of text):
4. Private Declare Function SendMessage Lib "User" (ByVal hWnd As Integer, ByVal
5. wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Any) As Long
6. Private Declare Sub GetCursorPos Lib "User" (lpPoint As POINTAPI)
7. Const WM_LBUTTONUP = &H202
8. Const WM_SYSCOMMAND = &H112
9. Const MOUSE_MOVE = &HF012
10. Add a Label control to Form1. Label1 is created by default. Set its Caption
property to "Thin Title Bar".
Note: For this example program, change the size of Form1 so that it resembles the
size and shape of a Toolbox window. Next, position the Label control at the top
of the form and adjust its size so that it isthe same size as a thin title bar.
11. Add the following code to the Click event for Label1:
12. Private Sub Label1_Click()
13. Dim mpos As POINTAPI
14. Dim P As ConvertPOINTAPI
15. Dim Ret As Integer
Abstract
This article explains how you can remove the title bar from a window or form from
within a Microsoft® Visual Basic® application.
First, we must first call GetWindowLong. This function reports the window style
associated with a window, among other pieces of information.
To use GetWindowLong, you must include its Declare statement in your program as
follows (note that the Declare statement must be typed as a single line of text):
Private Declare Function GetWindowLong Lib "User" (ByVal hWnd As Integer,
ByVal nIndex As Integer) As Long
The GetWindowLong function requires two arguments. The first argument is the
window's handle;the second argument specifies the type of information you want to
retrieve. In this case, we want to retrieve the window's style settings. The current window
style is returned as a long value after Get WindowLong is called.
After we have retrieved the current window style for the window, we need to save the
original style value that was just retrieved so that we can later restore the window's title
bar, if desired. This is done by testing for the individual title bar attributes and saving
each in turn to a new OriginalStyle variable. Next, we need to remove the attributes
associated with the window's title bar. These attributes are the Minimize and Maximize
buttons, the control menu, and the dialog box frame. We can remove them from the
original window style value that was just retrieved by using the bitwise AND NOT
function. Finally, we can call SetWindowLong to send this information to Windows,
which causes the title bar to be removed from the window.
Example Program
Thisprogram shows how you can remove and later restore a window's title bar.
15. Add a Command Button control to Form2. Command1 is created by default. Set
its Caption property to "OK".
16. Add the following code to the Click event for Command1:
17. Private Sub Command1_Click()
18. Form1.Show
19. Unload Form2
20. End Sub
21. From the Insert menu, select Module. Module1.Bas is created by default.
22. Add the following Constant and Declare statements to Module1.Bas (note that
each Declare statement must be typed as a single line of text):
23. Option Explicit
24. Private Declare Function GetWindowLong Lib "User" (ByVal hWnd As Integer,
25. ByVal nIndex As Integer) As Long
26. Private Declare Function SetWindowLong Lib "User" (ByVal hWnd As Integer,
27. ByVal nIndex As Integer, ByVal dwNewLong As Long) As Long
28. Const GWL_STYLE = (-16)
29. Const WS_DLGFRAME = &H400000
30. Const WS_SYSMENU = &H80000
31. Const WS_MINIMIZEBOX = &H20000
32. Const WS_MAXIMIZEBOX = &H10000
33. Create a new function called RemoveTitleBar to Module1.Bas. Add the
following code to this function:
34. Sub RemoveTitleBar(frm As Form)
35. Static OriginalStyle As Long
36. Dim CurrentStyle As Long
37. Dim X As Long
38. OriginalStyle = 0
39. CurrentStyle = GetWindowLong(frm.hWnd, GWL_STYLE)
40.
41. OriginalStyle = OriginalStyle Or (CurrentStyle And WS_DLGFRAME)
42. OriginalStyle = OriginalStyle Or (CurrentStyle And WS_SYSMENU)
43. OriginalStyle = OriginalStyle Or (CurrentStyle And WS_MINIMIZEBOX)
44. OriginalStyle = OriginalStyle Or (CurrentStyle And WS_MAXIMIZEBOX)
45.
Abstract
The Microsoft® Visual Basic® Text Box control lets your user enter text that can later
be used by your application. This article explains how you can center the text that the
user types vertically within the Text Box control.
Example Program
This program shows how to center text vertically within a Text Box control.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add a Picture Box control to Form1. Picture1 is created by default. Set its
AutoRedraw property to True.
3. Add a Text Box control to Form1 over top of the Picture Box control. Text1 is
created by default. Set its MultiLine property to True.
4. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that the Declare statement must be typed as a single line
of text):
5. Private Declare Function SendMessage Lib "User" (ByVal hWnd As Integer,
6. ByVal wMsg As Integer, ByVal wParam As Integer, lParam As Any) As Long
7. Const WM_USER = &H400
8. Const EM_GETLINECOUNT = WM_USER + 10
9. Dim NumLines As Integer
10. Add the following code to the Form_Load event for Form1:
11. Private Sub Form_Load()
12. Dim HT As Integer
13. Text1.Left = 0
14. Text1.Width = Picture1.Width
15. Text1.Height = Picture1.TextHeight("A")
16. Text1.Top = (Picture1.Height = Text1.Height) / 2
17. Text1.Visible = True
18. NumLines = 1
19. End Sub
20. Add the following code to the Change event for Text1:
21. Private Sub Text1_Change()
22. Dim Ret As Long
23. Dim HT As Integer
24. Ret = SendMessage(Text1.hWnd, EM_GETLINECOUNT, 0, ByVal 0&)
25. If Ret <> NumLines Then
26. HT = Picture1.TextHeight("A")
27. Text1.Height = HT * Ret
28. Text1.Top = (Picture1.Height - Text1.Height) / 2
29. NumLines = Ret
30. SendKeys "{PGUP}", True
31. Text1.SelStart = Len(Text1)
32. End If
33.
34. End Sub
Abstract
When developing an application in Microsoft® Visual Basic®, you may want to let the
user double-click the edit portion of a Combo Box control. This article explains how to
process this double-click event by using the Message Blaster custom control.
On the other hand, if you are using a Combo Box with its Style property set to 1 - Simple
Combo, the procedure is a little different. Because the edit portion of the Combo Box is
already displayed, you need to call GetWindow to retrieve the handle of the edit
window.
After you have retrieved the edit window's handle, you must call the GetClassName
function. This function is called so that we can be certain we are processing a double-
click message for only the edit portion of the Combo Box.
2. From the Insert menu, select Custom Control. Add the Message Blaster custom
control to this project.
4. Add the following code to the Message event for MsgBlaster1 (note that the first
two lines of code must be typed as a single line of text):
5. Private Sub MsgBlaster1_Message(MsgVal As Integer, wParam As Integer,
6. lParam As Long, ReturnVal As Long)
7. MsgBox "Combo1 box double-clicked"
8. End Sub
9. Add a Combo Box control to Form1. Combo1 is created by default. Set its Style
property to 1-Simple Combo.
10. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that each Declare statement must be typed as a single line
of text):
11. Private Declare Function GetWindow Lib "User" (ByVal hWnd As Integer,
12. ByVal wCmd As Integer) As Integer
13. Private Declare Function GetClassName Lib "User" (ByVal hWnd As Integer,
14. ByVal lpClassName As String, ByVal nMaxCount As Integer) As Integer
15. Const WM_LBUTTONDBLCLK = &H203
16. Const GW_CHILD = 5
17. Const GW_HWNDNEXT = 2
18. Add the following code to the Form_Load event for Form1:
19. Private Sub Form_Load()
20. Dim hWndList As Integer
21. Dim hWndEdit As Integer
22. Dim Buf As String * 10
23. Dim X As Integer
24.
25. Combo1.AddItem "Item #1"
26. Combo1.AddItem "Item #2"
27. Combo1.AddItem "Item #3"
28.
29. hWndList = GetWindow(Combo1.hWnd, GW_CHILD)
30. Select Case Combo1.Style
31.
32. Case 0
33. MsgBlaster1.hWndTarget = hWndList
34. MsgBlaster1.MsgList(0) = WM_LBUTTONDBLCLK
Abstract
When developing an application in Microsoft® Visual Basic®, you can use the
BackColor property to change the background color of a control. This article explains
how you can temporarily flash a control's BackColor property to draw the user's
attention to a specific control.
Example Program
This program shows how to highlight the control that has the focus. Run the example
program by pressing F5. Then click the Flash Command Button. Note that the
background color of the List Box control is changed to red and flashed three times.
14. Create a new function called FlashControl. Add the following code to this
function:
15. Sub FlashControl(C As Control)
16. Dim OldColor As Double
17. Dim Delay As Double
18. Dim X As Integer
19.
20. OldColor = C.BackColor
21. For X = 1 To 3
22. C.BackColor = QBColor(12)
23. Delay = Timer
24. While Timer - Delay < 0.2
25. DoEvents
26. Wend
27. C.BackColor = OldColor
28. Delay = Timer
29. While Timer - Delay < 0.2
30. DoEvents
31. Wend
32. Next X
Abstract
This article explains how you can create a multiple-document interface (MDI) form that
has a fixed border in a Microsoft® Visual Basic® application.
An MDI child form, however, does not have a BorderStyle property. But by using the
Microsoft Windows® GetWindowLong and SetWindowLong application programming
interface (API) functions , you can change an MDI form's border style to a fixed border
style.
The GetWindowLong function retrieves information about the specified window's style
attributes and the SetWindowLong function modifies the specified window's style
attributes.
GetWindowLong requires only two arguments. The first argument is the target window's
handle. The second argument specifies the type of information you want to retrieve,
which is the style settings for the window.
After retrieving the window's current style settings, use the bitwise And Not function to
remove the WS_THICKFRAME attribute from the style settings value. Next, issue a call
to the SetWindowLong function to set the new style settings for the specified window.
This creates an MDI form that has a fixed border style.
2. From the Insert menu, select MDI Form to create an MDI form. MDIForm1 is
created by default.
3. Set Form1's MDIChild property to True. Modify the size of this form so that it is
smaller than the MDIForm1 form.
4. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that each Declare statement must be typed as a single line
of text):
5. Private Declare Function GetWindowLong Lib "User" (ByVal hWnd As Integer, ByVal
6. nIndex As Integer) As Long
7. Private Declare Function SetWindowLong Lib "User" (ByVal hWnd As Integer, ByVal
8. nIndex As Integer, ByVal dwNewLong As Long) As Long
9. Const GWL_STYLE = (-16)
10. Const WS_THICKFRAME = &H40000
11. Add the following code to the Load event for MDIForm1 (note that the NewStyle
line must be typed as a single line of code):
12. Private Sub MDIForm_Load()
13. Dim CurStyle As Long
14. Dim NewStyle As Long
15. CurStyle = GetWindowLong(MDIForm1.hWnd, GWL_STYLE)
16. NewStyle = SetWindowLong(MDIForm1.hWnd, GWL_STYLE, CurStyle And
17. Not (WS_THICKFRAME))
18. End Sub
Abstract
In a Microsoft® Visual Basic® application, you can simulate a Click event to a
Command Button control. This article explains how to send a BN_CLICKED
notification message to a control.
As you can see from the example program below, the GetDlgCtrlID function retrieves
the Command Button's handle. Next, a call is made to the GetParent function, which
retrieves the handle of the window that the Command Button resides on. (In other
words, we must retrieve the parent window's handle.)
The last step is to execute a PostMessage function. PostMessage sends a BN_CLICKED
notification message to the parent window, which then processes the Click event for the
Command Button.
When you run the example program below, the second Command Button's Click event
is executed. However, the second Command Button does not receive the focus—only its
code is executed.
Example Program
This program shows how to send a Command Button click to the Windows operating
system.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that each Declare statement must be typed as a single line
of text):
3. Const BN_CLICKED = 0
4. Const WM_COMMAND = &H111
5. Private Declare Function GetDlgCtrlID Lib "User" (ByVal hWnd As Integer) As
6. Integer
7. Private Declare Function GetParent Lib "User" (ByVal hWnd As Integer) As Integer
8. Private Declare Function PostMessage Lib "User" (ByVal hWnd As Integer, ByVal
9. wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Long) As Integer
10. Add a Command Button control to Form1. Command1 is created by default. Set
its Caption property to "Send".
11. Add the following code to the Click event for Command1:
12. Private Sub Command1_Click()
13. ClickButton Command2.hWnd
14. End Sub
16. Add the following code to the Click event for Command2:
17. Private Sub Command2_Click()
18. MsgBox "Command2 was CLICKED!"
19. End Sub
20. Create a new function called ClickButton. Add the following code to this
function:
21. Sub ClickButton(ByVal hWnd As Integer)
22. Dim Button As Integer
23. Dim ParentHwnd As Integer
24. Dim X As Integer
25.
26. Button = GetDlgCtrlID(hWnd)
27. ParentHwnd = GetParent(hWnd)
28. X = PostMessage(ParentHwnd, WM_COMMAND, Button, BN_CLICKED * &H10000 +
hWnd)
29. End Sub
Run the example program by pressing F5. Click the Send Command Button. The Click
event for the second Command Button control is immediately executed (the message
box is displayed).
Abstract
The Microsoft® Visual Basic® List Box control lets you add individual items to create a
list of data. This article explains how to add tab stops to create multicolumn items, no
matter what type of font or font size is used.
Example Program
This program shows how to add tab stops to a List Box control. No matter what font or
font size is used when adding items to the control, the columns will line up correctly.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that each Declare statement must be typed as a single line
of text):
3. Private Declare Function Getfocus Lib "User" () As Integer
4. Private Declare Function GetDialogBaseUnits Lib "User" () As Long
5. Private Declare Sub SendMessage Lib "User" (ByVal hWnd As
6. Integer, ByVal wMsg As Integer, ByVal wParam As Integer, lParam As Any)
7. Private Declare Sub APISetFocus Lib "User" Alias "SetFocus"
8. (ByVal hWnd As Integer)
9. Const WM_USER = &H400
10. Const LB_SETTABSTOPS = WM_USER + 19
11. Add the following code to the Form_Load event for Form1:
12. Private Sub Form_Load()
13. Dim TB As String * 1
14. Dim OldHandle As Integer
15. Dim ListHandle As Integer
16. Dim DlgWidthUnits As Integer
17. Dim I As Integer
18. ReDim TabStop(2) As Integer
19.
20. TabStop(0) = 10
21. TabStop(1) = 30
22. TabStop(2) = 50
23.
24. TB = Chr$(9)
25. Show
26. OldHandle = Getfocus()
27. List1.SetFocus
28. ListHandle = Getfocus()
29. DlgWidthUnits = (GetDialogBaseUnits() Mod 65536) / 2
30.
31. For I = 0 To 2
32. TabStop(I) = TabStop(I) * DlgWidthUnits
33. Next I
34.
35. Call SendMessage(ListHandle, LB_SETTABSTOPS, 3, TabStop(0))
36. Call APISetFocus(OldHandle)
37. List1.AddItem "Item" + TB + "Quan." + TB + "Price"
38. List1.AddItem "Disks" + TB + "10" + TB + "$9.50"
39. List1.AddItem "Paper" + TB + "12" + TB + "$22.50"
40. End Sub
Abstract
When you change the ListIndex property of a Combo Box control, the Click event is
automatically triggered. This article explains how to suppress this Click event.
To prevent a Click event from being triggered each time the ListIndex property is
changed, you need only send the CB_SETCURSEL message directly to the control. The
Click event is not generated, but the individual item is still selected or deselected.
Example Program
The example program below shows how to set the ListIndex property of a Combo Box
control without generating a Click event.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that the Declare statement must be typed as one single line
of code):
3. Private Declare Function SendMessageByString Lib "User" Alias "SendMessage"
4. (ByVal hWnd As Integer, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal
5. lParam As String) As Integer
6. Const WM_USER = &H400
7. Const CB_SETCURSEL = (WM_USER + 14)
8. Add the following code to the Form_Load event for Form1:
9. Private Sub Form_Load()
10. Combo1.AddItem "Item #1"
11. Combo1.AddItem "Item #2"
15. Add the following code to the Click event for Combo1:
16. Private Sub Combo1_Click()
17. MsgBox "Combo1 was Clicked!"
18. End Sub
19. Add a Command Button control to Form1. Command1 is created by default. Set
its Caption property to "Will Click".
20. Add the following code to the Click event for Command1:
21. Private Sub Command1_Click()
22. Combo1.ListIndex = 1
23. End Sub
24. Add a second Command Button control to Form1. Command2 is created by
default. Set its Caption property to "Will Not Click".
25. Add the following code to the Click event for Command2:
26. Private Sub Command2_Click()
27. SetComboListIndex Combo1, 1
28. End Sub
29. Create a new function called SetComboListIndex. Add the following code to this
function:
30. Sub SetComboListIndex(cboCombo As ComboBox, iIndex As Integer)
31. Dim R As Integer
32. R = SendMessageByString(cboCombo.hWnd, CB_SETCURSEL, iIndex, "")
33. End Sub
Run the example program by pressing the F5 function key. Click the "Will Click"
command button. A message box is displayed indicating that the Click event was
triggered when the ListIndex property was changed. Click the "Will Not Click"
command button. The item in the Combo Box is selected but a Click event is not
triggered.
Abstract
When developing an application in Microsoft® Visual Basic®, you may need to design a
transparent form. This article explains how to create transparent forms.
To use the SetWindowLong function within your Microsoft Visual Basic® program,
include the following Declare statement in the General Declarations section of a form
(note that it must be typed as a single line of code):
Private Declare Function SetWindowLong Lib "User" (ByVal hWnd As Integer, ByVal
nIndex As Integer, ByVal dwNewLong As Long) As Long
The SetWindowLong function takes the following arguments.
hWnd An integer value containing the window's handle.
nIndex An integer value that describes the type of information you want to set.
This value may be one of the following:
GWL_EXSTYLE Set the extended window style
GWL_STYLE Set the window style
GWL_WNDPROC The window function's address
dwNewLong A long value containing the new style bits to be given to the window.
Because you want to make the specified form transparent, you call the SetWindowLong
function with the nIndex argument set to GWL_EXSTYLE, specifying the transparency
style bit.
When you run the example program shown below, the form will be displayed in
transparent mode.
Example Program
This program shows how to create a transparent form.
1. Create a new project in Visual Basic. Form1 is created by default. Set the form's
Picture property to the ARCHES.BMP bitmap file (usually found in the
\WINDOWS directory).
8. Add the following Constant and Declare statements to the General Declarations
section of Form2 (note that the Declare statement must be typed as one single line
of code):
9. Private Declare Function SetWindowLong Lib "User" (ByVal hWnd As Integer, ByVal
10. nIndex As Integer, ByVal dwNewLong As Long) As Long
11. Const WS_EX_TRANSPARENT = &H20&
12. Const GWL_EXSTYLE = (-20)
13. Add the following code to the Form_Load event for Form2:
14. Private Sub Form_Load()
15. Dim Ret As Long
16. Ret = SetWindowLong(Form2.hWnd, GWL_EXSTYLE, WS_EX_TRANSPARENT)
17. End Sub
Run the example program by pressing F5. Click the "Show Form" command button.
Form2 is displayed directly over Form1. It appears as if only Form1 is displayed because
Form2 has the transparent attribute.
Abstract
The Microsoft® Windows® application programming interface (API) SendMessage
function can be used to send messages to Microsoft Visual Basic® controls such as Text
Boxes. This article explains how you can prevent text from scrolling in a Text Box
control. The nonscrolling portion of the control can also be made invisible to the user.
You may want to substitute the EM_SETRECT message for the EM_SETRECTNP
message. Using EM_SETRECT stops Windows from redrawing the text in the formatting
rectangle area. This results in the text being invisible within the Text Box control.
Example Program
This program shows how to temporarily freeze a specific portion of a Text Box control.
The frozen portion contains the text that will not be scrolled out of view.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that the Declare statement must be typed as one single line
of code):
3. Private Declare Function SendMessage Lib "User" (ByVal hWnd As Integer, ByVal
4. wMsg As Integer, ByVal wParam As Integer, lParam As Any) As Long
5. Const WM_USER = &H400
6. Const EM_SETRECTNP = WM_USER + 4
7. Const EM_SETRECT = WM_USER + 3
8. Add the following code to the Form_Load event for Form1:
9. Private Sub Form_Load()
10. Text1.Text = "This is the first paragraph that we want to show."
11. Text1.Text = Text1.Text & " in the Text Box control"
12. Text1.Text = Text1.Text & Chr$(13) & Chr$(10) & "This is the second paragraph that we"
13. Text1.Text = Text1.Text & " want to freeze so that text cannot be scrolled"
14. End Sub
15. Add the following code to the Click event for Form1:
16. Private Sub Form_Click()
17. Dim R As RECT
18. Dim X As Long
19.
20. ScaleMode = 3
21.
22. R.Left = 0
Abstract
The Combo Box control in Microsoft® Visual Basic® allows your user to easily select
items by clicking the desired entry in the control. This article explains how you can add a
smart search feature to the Combo Box control.
A smart search means that the user can type the first few letters of an entry, and the first
entry in the list that matches these characters will be displayed in the edit portion of the
Combo Box control.
The example program below shows how to implement a smart search routine in your
Visual Basic application. The trick to doing this search lies in the KeyPress event of the
Combo Box control.
Each time the user presses a key on the keyboard, the KeyPress event is triggered. These
keystrokes can be trapped and acted upon in whatever fashion you want. As an example,
in the smart search routine we automatically ignore all keyboard characters that have an
ASCII value of less than 32 or greater than 127. This lets us process only alphabetic
characters (A–Z, a–z), numeric characters (0–9), and punctuation characters (exclamation
point, comma, and so forth).
It is a simple matter to save the characters that the user types to a string variable such as
FindString and then to use the Microsoft Windows® application programming interface
(API) SendMessage function to execute a CB_FINDSTRING message to the Combo
Box control.
The CB_FINDSTRING message lets you search a Combo Box control for an entry that
matches the target string. This function requires two arguments—the number of the item
in the control from which you want the search to start, and the string you want to find. To
search the entire Combo Box control, you set the first argument to a value of -1.
After you have executed the CB_FINDSTRING message, it will return the number of the
matching entry. You can then use this to display the result to the user in the edit portion
of the Combo Box control.
Example Program
This program shows how to perform a "smart search" with a Combo Box control.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that the Declare statement must be typed as a single line
of code):
16. Add the following code to the KeyPress event for Combo1:
17. Private Sub Combo1_KeyPress(KeyAscii As Integer)
18. Dim CB As Long
19. Dim FindString As String
20.
21. If KeyAscii < 32 Or KeyAscii > 127 Then Exit Sub
22.
23. If Combo1.SelLength = 0 Then
24. FindString = Combo1.Text & Chr$(KeyAscii)
25. Else
26. FindString = Left$(Combo1.Text, Combo1.SelStart) & Chr$(KeyAscii)
27. End If
28.
29. CB = SendMessage(Combo1.hWnd, CB_FINDSTRING, -1, ByVal FindString)
30.
31. If CB <> CB_ERR Then
32. Combo1.ListIndex = CB
33. Combo1.SelStart = Len(FindString)
34. Combo1.SelLength = Len(Combo1.Text) - Combo1.SelStart
35. End If
36. KeyAscii = 0
37. End Sub
Run the example program by pressing F5. Type the text you want to find. As you enter
each character, the KeyPress event is triggered. For example, type the letter i. The item
ice appears in the Combo Box's edit window. Try again, this time typing the word ice
followed by a space character. The Combo Box displays ice cream. Try typing a word
that is not in the list, such as potato. The Combo Box will respond by finding the closest
match—in this case, the Onion rings entry.
Abstract
In a Microsoft® Visual Basic® application, you can send data to the printer by using the
Print method. The printed output appears in the default portrait orientation. This article
shows how to change the orientation of the printer from its default portrait mode to
landscape mode.
Most printers manufactured today support a number of functions such as changing the
print orientation to landscape mode. You tell the printer driver to select landscape
printing by sending specific control code commands to the device. In Windows
terminology, these control code commands are called Escape operations.
The example program below shows how to use the Windows API Escape function to
change the orientation of the printer. When you run this program, notice that a blank
piece of paper is not ejected when the setting takes effect.
How do we prevent the blank sheet of paper from being ejected? The AbortDoc function
tells Windows to ignore the previous print request. This generates a printer error, which is
trapped by the On Error Resume Next statement. Therefore, the printer is set to the new
orientation without ejecting a blank piece of paper.
The Escape function can be used to send specific control codes to a printer device. The
CONSTANT.TXT file contains a list of the most commonly used escape codes that can
be used with printers, display screens, and other devices.
To use the Escape function within your program, include the following Declare
statement in the General Declarations section of your form (note that this Declare
statement must be typed as a single line of text):
Private Declare Function Escape Lib "GDI" (ByVal hDC As Integer, ByVal nEscape
As Integer, ByVal nCount As Integer, lpInData As Any, lpOutData As Any) As
Integer
The Escape function requires five arguments, as follows.
hDC An integer value containing the device context's handle
nEscape An integer value containing the specific escape code to be sent to the
device context
nCount An integer value set to the size of the lpInData argument
lpInData Varies—see below
The arguments lpInData and lpOutData are set according to which escape code is being
sent to the printer. Because we want to set the printer to either landscape or portrait mode,
we specify the nEscape argument as GETSETPRINTORIENT. The
GETSETPRINTORIENT operation requires that the arguments lpInData and lpOutData
point to a 20-byte structure. To actually set the orientation, the first long value in this
structure must be set to the specific orientation you want to use.
After the escape code (landscape or portrait) is sent to the printer, you must use the
Windows API AbortDoc function. This function tells the printer to abort the print
request. Calling the AbortDoc function sets the printer to the new mode. All subsequent
output to the printer will then print in whichever print orientation you selected. This
means that you may have to issue another Escape statement to reset the printer to portrait
mode to return the printer to its default state.
Example Program
This program shows how to set the printer to landscape (or portrait) mode.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that each Declare statement must be typed as a single line
of code):
3. Private Declare Function AbortDoc Lib "GDI" (ByVal hDC As Integer) As Integer
4. Private Declare Function Escape Lib "GDI" (ByVal hDC As Integer, ByVal
5. nEscape As Integer, ByVal nCount As Integer, lpInData As Any, lpOutData As
6. Any) As Integer
7. Const PORTRAIT = 1
8. Const LANDSCAPE = 2
9. Const GETSETPAPERORIENT = 30
10. Const NULLVALUE = 0&
11. Add a Command Button control to Form1. Command1 is created by default. Set
its Caption property to "Landscape".
12. Add the following code to the Click event for Command1:
13. Private Sub Command1_Click()
14. PrintOrient LANDSCAPE, "This is landscape printing."
15. End Sub
16. Add a second Command Button control to Form1. Command2 is created by
default. Set its Caption property to "Portrait".
17. Add the following code to the Click event for Command2:
18. Private Sub Command2_Click()
19. PrintOrient PORTRAIT, "This is portrait printing."
Abstract
When you use the Menu Editor in Microsoft® Visual Basic®, you can assign a shortcut
or accelerator key to each individual menu entry. This article shows how you can change
this shortcut key at run time within your Visual Basic application.
To change a menu entry's access key at run time, you need to process the keystrokes at
the form-level. That is, the KeyDown event for the underlying form will need to be
monitored.
The KeyDown event in Visual Basic is triggered each time a user presses a key on the
keyboard. The event is triggered for the control that has the focus. In this case, the control
is the form that the menu is attached to.
The KeyDown event tells you which key or combination of keys was just pressed on the
keyboard. The KeyCode argument gives you a unique number that identifies each
individual key on the keyboard. For example, if the KeyCode value returned is 9, you
know that the TAB key was just pressed.
In the example program below, you use the KeyDown event to determine if the user
pressed the CTRL+E keystroke combination. If CTRL+E was pressed, the program
displays a message box telling you that the File menu item was selected. In all other
cases, the KeyDown event simply ignores the incoming keystrokes.
Example Program
This program shows how to change a menu item's shortcut key from within a Visual
Basic application.
1. Create a new project in Visual Basic. Form1 is created by default.
23. Add the following code to the Click event for Command1:
24. Private Sub Command1_Click()
25. ShortCut = "E"
26. mnuFile.Caption = "Fil" & "&" & LCase$(ShortCut)
27. End Sub
Run the example program by pressing F5. Notice the menu at the top of the form. The
menu entry says "File" with the letter F underlined. The letter F is the menu entry's
access key. Click the command button. The menu changes to "File" with the letter e
designated as the access key. Press CTRL+E on the keyboard; a message box pops up
saying that that menu item was just clicked.
Abstract
In a Microsoft® Visual Basic® application, you may need to convert a Microsoft Word
for Windows® version 6.0 document to rich-text format (RTF). This article explains how
this can be accomplished in Visual Basic.
In the same manner, you use the object variable to tell Word to save the document (using
the WordBasic FileSaveAs command) in RTF format. You must specify both a file name
for the document and the file format in which you want to save the document. Because
you want to save the file as an RTF document, specify the value 6 for RTF.
After Word has saved the document in RTF format, you want to exit Word and return to
your Visual Basic application. This is done by setting the object variable to Nothing,
which closes the server application.
Example Program
This program shows how to use OLE Automation to convert a Microsoft Word for
Windows 6.0 document to RTF format from within a Visual Basic application.
1. Create a new project in Visual Basic. Form1 is created by default.
Abstract
You can add many different controls, such as Text Boxes, to your Microsoft® Visual
Basic® forms. At design time, you can adjust the size and position of the control. This
article explains how the user can modify the size of these controls at run time from within
a Visual Basic application.
The final step is to anchor the newly sized Text Box so that its new position and size is
registered on the underlying form. The SetWindowPos function accomplishes this task.
Example Program
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that each Declare statement must be typed as a single line
of code):
3. Private Declare Function GetWindowLong Lib "User" (ByVal hWnd As Integer, ByVal
4. nIndex As Integer) As Long
5. Private Declare Function SetWindowLong Lib "User" (ByVal hWnd As Integer, ByVal
6. nIndex As Integer, ByVal dwNewLong As Long) As Long
7. Private Declare Sub SetWindowPos Lib "User" (ByVal hWnd As Integer, ByVal
8. hWndInsertAfter As Integer, ByVal X As Integer, ByVal Y As Integer, ByVal CX
9. As Integer, ByVal CY As Integer, ByVal wFlags As Integer)
10. Const SWP_NOSIZE = &H1
11. Const SWP_NOZORDER = &H4
12. Const SWP_NOMOVE = &H2
13. Const SWP_DRAWFRAME = &H20
14. Const GWL_STYLE = (-16)
15. Const WS_THICKFRAME = &H40000
16. Add a Command Button control to Form1. Command1 is created by default.
17. Add the following code to the Click event for Command1:
18. Private Sub Command1_Click()
19. ResizeControl Text1, Form1
20. End Sub
21. Add a Text Box control to Form1. Text1 is created by default.
22. Create a new function called ResizeControl. Add the following code to this
function:
23. Function ResizeControl(ControlName As Control, FormName As Form)
24. Dim NewStyle As Long
25. NewStyle = GetWindowLong(ControlName.hWnd, GWL_STYLE)
26. NewStyle = NewStyle Or WS_THICKFRAME
27. NewStyle = SetWindowLong(Text1.hWnd, GWL_STYLE, NewStyle)
28. SetWindowPos ControlName.hWnd, FormName.hWnd, 0, 0, 0, 0, SWP_NOZORDER Or
SWP_NOSIZE Or SWP_NOMOVE Or SWP_DRAWFRAME
29. End Function
Run the example program by pressing F5 Click the command button. You can now make
the Text Box any size you want.
Let's assume that each time you load Visual Basic in order to design a new project, you
want to minimize Program Manager. After you have finished working in Visual Basic,
you want Program Manager to be restored to its normal, maximized state.
To accomplish this task in Visual Basic, you need to use two Windows application
programming interface (API) functions. The FindWindow function returns the handle of
the window that matches the name of your target window. In this case, you want to find
the handle of the window belonging to Program Manager. Therefore, you tell
FindWindow to find the first window whose window name is "Program Manager".
When you have the Program Manager window handle, you use the WindowState
property in Visual Basic to minimize your program's window. This means that your
Visual Basic program runs quietly in the background, waiting for Visual Basic to be run.
Approximately once every second, the program checks the computer system to see
whether Visual Basic has been run. This is done in the Timer1 routine in the example
program that follows. If the FindWindow function determines that Visual Basic is
running in memory, it uses the ShowWindow function to minimize the Program
Manager window. Alternatively, if the FindWindow function finds that Visual Basic is
not running, it tells ShowWindow to maximize the Program Manager window.
You can modify this example program to monitor any Windows-based application. In
addition, you might want to add this program to your Windows Startup group so that it
runs each time you start Windows.
Example Program
This program shows how to minimize Program Manager each time you run Visual Basic.
When you quit Visual Basic, Program Manager is restored to its original, maximized
state.
1. Create a new project in Visual Basic. Form1 is created by default.
25. Add the following code to the Timer1 event for Timer1:
26. Private Sub Timer1_Timer()
27. vb_hwnd = FindWindow(ByVal 0&, ByVal VBS)
28. If Flag = False Then
29. If vb_hwnd <> 0 Then
30. Flag = True
31. R = ShowWindow(pm_hwnd, SW_MINIMIZE)
32. End If
33. Else
34. If vb_hwnd = 0 Then
35. Flag = False
36. R = ShowWindow(pm_hwnd, SW_RESTORE)
37. End If
38. End If
39. End Sub
40. On the File menu in Visual Basic, click Make EXE File. Save the file as
MINPM.EXE.
On the File menu in Program Manager, click Run. Type the program's name as
MINPM.EXE and click OK. The MINPM program is now running in memory. When you
start Visual Basic, Program Manager will be minimized on the desktop. As soon as you
quit Visual Basic, Program Manager will be maximized.
Abstract
The Text Box control in Microsoft® Visual Basic® is a mini-word-processing program
that lets your user type either single or multiple lines of text. At design time, you set the
MultiLine property either to False (single) or to True (multiline). This property cannot be
changed at run time. However, during run time you can use Scroll Bar controls to give
the impression that your Text Box can be made single or multiline at run time, regardless
of the MultiLine property setting.
To disable the scroll bars in this Visual Basic program, you simply call SetScrollRange
with the minimum and maximum position indicators set to the same value. When you
want to enable the scroll bars again, you call SetScrollRange with the minimum and
maximum position indicators set to 1 and 100, respectively. When you change the
position indictors to 1 and 100, you can scroll through the contents of the Text Box
control regardless of the MultiLine property setting. This gives the impression that the
Text Box control is MultiLine when it is indeed set to single-line status.
Example Program
This program shows how to create a Text Box control that can be switched at run time
from single-line to multiline status, with or without scroll bars.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that the Declare statement must be typed as a single line
of text):
3. Private Declare Sub SetScrollRange Lib "User" (ByVal hWnd As Integer,
4. ByVal nBar As Integer, ByVal nMinPos As Integer,
5. ByVal nMaxPos As Integer, ByVal bRedraw As Integer)
6. Const ESB_DISABLE_BOTH = 3
7. Const ESB_ENABLE_BOTH = 1
8. Add a Text Box control to Form1. Text1 is created by default. Set its MultiLine
property to True. Set its ScrollBars property to 3-Both.
10. Add the following code to the Click event for Command1:
11. Private Sub Command1_Click()
12. Dim hWnd As Integer
13. Dim Min As Integer
14. Dim Max As Integer
15. Min = 1
16. Max = Min
17. Call SetScrollRange(Text1.hWnd, ESB_DISABLE_BOTH, Min, Max, 1)
20. Add the following code to the Click event for Command2:
21. Private Sub Command2_Click()
22. Dim hWnd As Integer
23. Dim Min As Integer
24. Dim Max As Integer
25. Min = 1
26. Max = 100
27. Call SetScrollRange(Text1.hWnd, ESB_ENABLE_BOTH, Min, Max, 1)
28. End Sub
Run the example program by pressing F5. Click the Text Box control and type several
lines of text. Notice that you can use the scroll bars to scroll through the text in the
control. Click Disable. Now you cannot use the scroll bars to scroll through the Text Box
control. To enable the scroll bars again, click Enable.
Abstract
The IS operator in Microsoft® Visual Basic® lets you determine whether the names of
two variables refer to the same object (a control or form). This article explains how you
can compare two object variables to determine whether they are the same entity.
Example Program
This program shows how to compare two Visual Basic objects to see whether they are
identical.
Abstract
Example Program
This program shows how to display specific fields from a Microsoft Access database in a
Visual Basic Outline control.
Abstract
The Drive List Box control in Microsoft® Visual Basic® reports the names of each drive
connected to the computer system. This article explains another method you can use to
determine which disk drives are available.
In the example program, you use a For-Next loop to cycle through all possible disk drives
that may be installed in the computer system. Each time through the loop, you ask
CurDir$ to change to a new, higher disk drive letter. When the function reports that it
cannot switch to the specified drive, you know that you have found the last available disk
drive.
Example Program
This program shows how to retrieve all valid disk drives without using a Drive List Box
control.
1. Create a new project in Visual Basic. Form1 is created by default.
Abstract
When designing a Microsoft® Visual Basic® application, you may need to use an
installation program to compress and decompress files needed by your program. This
article explains how to retrieve the original file name of a compressed file.
After this function is called, a value greater than zero will be returned if the operation
was successful. If the function was not successful, a negative value will be returned.
Example Program
This program shows how to retrieve the full name of a file that was previously
compressed by the COMPRESS.EXE program.
1. Create a new project in Visual Basic. Form1 is created by default.
Abstract
The List Box control in Microsoft® Visual Basic® provides a method of sorting a list of
items in alphabetic order. This article explains how you can sort the items in a List Box
control in descending order.
You can sort the items contained in a List Box control by setting the control's Sorted
property to True. The items will be sorted in ascending alphabetic (A–Z) order. However,
if you want to sort the items in descending order, you need to use two List Box controls.
The example program uses two List Box controls. The first List Box contains the items
you want to sort. The Visible property of this List Box is set to False, because it is your
"working" List Box control. You don't want to see the contents of this control at run time.
In addition, the Sorted property of the List Box is set to True. Each item you add to this
List Box control is stored in ascending order.
The second List Box control used in this program will display the final result of your sort
routine. Its Visible property is set to True and its Sorted property is set to False.
In the example program below, you simply copy the desired items you want to sort from
the first List Box control to the second List Box control. To do this, you use a For-Next
loop. The ListCount property of a List Box control tells you how many entries are stored
in the control. You use this value (minus 1, because you start counting from zero) to step
backwards from the end of the list to the beginning. Each time you cycle through the For-
Next loop, you add the current item to the second List Box control. This stores the final
list of items in descending (Z–A) order in the second List Box control.
Example Program
This program shows how to reverse-sort the contents of a List Box control.
11. Add a second List Box control to Form1. List2 is created by default. Set its
Sorted property to False.
13. Add the following code to the Click event for Command1:
14. Private Sub Command1_Click()
15. Dim X As Integer
16. For X = List1.ListCount - 1 To 0 Step -1
17. List2.AddItem List1.List(X)
18. Next X
19. End Sub
Run the example program by pressing F5. Click the command button. The List Box
control is populated with the entries from the first (hidden) List Box control. These
entries are sorted in descending order, from Z through A.
Abstract
While your Microsoft® Visual Basic® program is running, you may need to update the
date and time stamp for a particular file. This article explains how you can set a file's date
and time stamp to the current date and time setting.
Example Program
This program shows how to update a file's date and time information from within a
Visual Basic application.
Abstract
When developing an application in Microsoft® Visual Basic®, you may need to calculate
the specific date of the first and last days of a month. This article explains how to
accomplish this task in Visual Basic.
In the example program below, you want to find the first and last dates in the month of
July, 1995. To do this, you convert the string date (July 3, 1995) to a date serial number.
Then you use the DateSerial function in conjunction with the Year and Month functions
to calculate the first date in the month of July. You repeat this routine to determine the
last date in the month of July.
After calling the DateSerial function, you must use the Visual Basic Year, Month, and
Day functions to extract and decode specific portions of information from the date serial
number. You must do this because the date serial number is encoded in a special format.
In the example program below, you use the Year and Month functions to determine
which date is the first day of the month. The Month function returns a value of 1 through
12 that represents the specified month. In a similar fashion, the Visual Basic Year
function returns the year from the encoded serial number.
Example Program
This program shows how to retrieve the first and last date for a specified month.
2. Add a Text Box control to Form1. Text1 is created by default. Set its MultiLine
property to True.
Abstract
The List Box control in Microsoft® Visual Basic® lets you easily manage related pieces
of information. You use the AddItem method to add new items to the list and the
RemoveItem method to delete items from the list. This article explains how to set the
focus to the next item in the List Box control after deleting the currently selected item.
However, when you delete an item from the list, the focus does not automatically change
to the next available item in the list. The example program below shows how to do this.
The ListIndex property of a List Box control tells you which item was selected by the
user. Knowing this value, you can use the RemoveItem method to delete that specific
entry from the list. For example, if you select the third item in the List Box control, the
ListIndex property would be set to a value of two (the List Box control starts numbering
the entries from zero).
It is a simple matter, then, to set the focus to the next available item in the list by keeping
track of your position within the list. After deleting the selected item, you set the
ListIndex property to your current position minus one. You can then set the focus to this
newly selected item.
Example Program
This program shows how to delete an item from a List Box control and set the focus to
the next available item in the list.
12. Add the following code to the Click event for Command1:
13. Private Sub Command1_Click()
14. Dim PositionInList As Integer
15. Dim NumberOfItemsInList As Integer
16. PositionInList = List1.ListIndex
17. NumberOfItemsInList = List1.ListCount
18. If NumberOfItemsInList > 0 Then
19. If PositionInList >= 0 Then
20. List1.RemoveItem PositionInList
21. Else
22. MsgBox "You must select an item to delete.", 48, "Error"
23. End If
24. Else
25. MsgBox "There are no items to delete.", 48, "Error"
26. End If
27. NumberOfItemsInList = List1.ListCount
28. If NumberOfItemsInList > 0 Then
29. If PositionInList = NumberOfItemsInList Then
30. List1.ListIndex = NumberOfItemsInList - 1
31. Else
32. List1.ListIndex = PositionInList
33. End If
34. End If
35. List1.SetFocus
36. End Sub
Run the example program by pressing F5. Five items will appear in the List Box control.
Notice that no items are selected. Click the Delete command button. A message box is
displayed, indicating that you must select an item before you can delete it.
Click the OK command button. Click the third item (Item #3) to select it. The item is
deleted from the List Box control, and the focus is moved to the next available item in
the list.
Notice that if you attempt to delete an item that does not exist in the List Box control, a
message box will be displayed, telling you that there are no items to delete.
Abstract
Almost all Microsoft® Windows®-based applications provide an Edit menu on which
you can select the Undo command to reverse the most recently made changes to an edit
control. This article explains how you can add this functionality to your own Microsoft
Visual Basic® application.
As shown in the example program below, you can also determine whether an undo
operation can be performed on the edit control. The EM_CANUNDO message returns an
integer value set to True if there is text in the undo buffer, or zero if no text is available.
You can perform an undo operation only if the contents of an edit control have been
previously modified and the data is stored in the undo buffer.
Example Program
This program shows how to add the Undo and Redo editing features to your Visual Basic
application.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that the Declare statement must be typed as a single line
of code):
10. Add a Command Button control to Form1. Command1 is created by default. Set
its Caption property to "Undo".
11. Add the following code to the Click event for Command1:
12. Private Sub Command1_Click()
13. Dim OK As Long
14. OK = SendMessage(Text1.hWnd, EM_UNDO, 0, 0&)
15. OK = SendMessage(Text1.hWnd, EM_EMPTYUNDOBUFFER, 0, 0&)
16. End Sub
17. Add a second Command Button control to Form1. Command2 is created by
default. Set its Caption property to "Redo".
18. Add the following code to the Click event for Command2:
19. Private Sub Command2_Click()
20. Dim OK As Long
21. OK = SendMessage(Text1.hWnd, EM_CANUNDO, 0, 0&)
22. If OK = 0 Then
23. MsgBox "Cannot undo the changes you made", 16, "Error"
24. End If
25. OK = SendMessage(Text1.hWnd, EM_UNDO, 0, 0&)
26. End Sub
Run the example program by pressing F5. Type some text into the Text Box control.
Assume that you typed the line, "We will go shopping on Monday and Tuesday." Select
the words "Monday and". Press DEL to delete the text. Click the Redo command button.
The original sentence is restored. Click Redo a second time. The modified sentence is
restored. The Redo function is similar to the cut-and-paste functions you see in word-
processing programs.
Select the words "Monday and" a second time and again delete the text. Click Undo to
restore the original text. Notice that clicking the Undo command button a second time
does nothing. This is because the Undo routine clears the undo flag and the edit buffer.
You can only undo one change at a time.
However, you must take into consideration whether you are programming in a 16-bit or
32-bit environment. If you're running in a 16-bit environment, then you can only use 16-
bit DLL functions. However, if you're running in a 32-bit environment, you may be able
to make calls to 16-bit and 32-bit functions, depending on the environment in question.
Because your application may be run on many different operating systems (Windows
version 3.1, Windows 95, OS/2®, Windows NT™, and so on), you need to find out
whether files are 16-bit or 32-bit. Then you can determine which API functions can be
used in your Visual Basic program.
In the example program below, you can type the full path of a file you want to check.
When you click the command button, the program reads data from the header block of
the file and reports its file type.
Each time an operating system saves a file on disk, the operating system prefixes the file
with a header block as the first data stored in the file. This header block contains
information that can be used to identify the file's type. For example, an MS-DOS® file
has a header containing the two characters "MZ". When you run the ExeType function
on this file, you would know that it is either a .COM, .CMD, .PIF, or .BAT file if the file
contains the "MZ" signature in its header block.
Example Program
This program shows how you can identify individual file types.
23. Add the following code to the Click event for Command1:
24. Private Sub Command1_Click()
25. If Text1.TEXT = "" Then
26. Exit Sub
27. End If
28. Dim X As Integer
29. Dim FileToCheck As String
30. FileToCheck = Text1.TEXT
31. X = ExeType(FileToCheck)
32. If X = errNoFile Then
33. MsgBox "File does not exist", 16, "Error"
34. Exit Sub
35. End If
36. Select Case X
37. Case ordMSDOS
38. MsgBox "File is MSDOS EXE file", 16, "OK"
39. Case ordWindows
40. MsgBox "File is a Windows file", 16, "OK"
41. Case ordOS2_1
42. MsgBox "File is OS/2 1.x file", 16, "OK"
43. Case ordNTWin
44. MsgBox "File is NT Windows file", 16, "OK"
45. Case ordNTChar
46. MsgBox "File is NT character file", 16, "OK"
47. Case ordDOSUnknown
48. MsgBox "File is probably DOS extended file", 16, "OK"
49. Case ordNotExe
50. MsgBox "File is not MSDOS EXE file", 16, "OK"
51. Case errOS2_2
52. MsgBox "File is OS/2 LE file", 16, "OK"
53. Case errWinOS2DLL
54. MsgBox "File is a DLL executable but not by us", 16, "OK"
55. Case errNEUnknown
56. MsgBox "File is unknown NE system", 16, "OK"
Abstract
You can maintain a list of items in the Microsoft® Visual Basic® List Box control. This
article explains how to add new items to the List Box control by first checking to see if
the entry already exists in the list.
The LB_FINDSTRING message lets you search a List Box control for an entry that
matches the target string. The first argument to this message defines the type of search
you want to perform. You need to specify a value of zero to begin the search operation at
the first entry in the List Box control. The second argument to the LB_FINDSTRING
message is a NULL-terminated string that is the actual item you want to search for.
If the LB_FINDSTRING message returns a value of –1 (minus 1), you know that the
target string was not found in the List Box control. You can then use the AddItem
method to add the new item to the List Box control. If the item already exists in the list,
however, you can simply display a message box or perform some other procedure to
inform the user that a duplicate entry already exists in the List Box control.
Example Program
This program shows how to determine if a List Box control already contains the item you
are trying to add to the control.
17. Add a Command Button control to Form1. Command1 is created by default. Set
its Caption property to "Duplicate".
18. Add the following code to the Click event for Command1:
19. Private Sub Command1_Click()
20. CheckForDupes
21. End Sub
22. Create a new function called CheckForDupes. Add the following code to this
function:
23. Sub CheckForDupes()
24. Dim Ret As Long
25. Dim A As String
26. A = Text1.TEXT
27. Ret = SendMessageFind(List1.hwnd, LB_FINDSTRING, 0, (A))
28. If Ret = LB_ERR Then
29. List1.AddItem Text1.TEXT
30. Else
31. List1.ListIndex = Ret
32. MsgBox "Duplicate entry - cannot add to List Box", 16, "Error"
33. End If
34. End Sub
Run the example program by pressing F5. The List Box control has five items in it. Type
a new entry in the Text Box control. Click the Duplicate command button. The program
searches the List Box control for the entry you typed in the Text Box control. If the entry
was not found, the program adds it to the List Box control. Alternatively, if the entry
already exists in the List Box control, a message box is displayed informing you of this
fact.
Abstract
In Microsoft® Visual Basic®, you can programmatically scroll through the contents of a
Text Box control without actually waiting for your user to click the Scroll Bar control.
You can do this by sending one of the scrolling messages to the system with the
Microsoft Windows® application programming interface (API) SendMessage function.
As you can see from the list above, to scroll the contents of the Text Box left by one
character, you set the wParam argument to SB_LINELEFT. To scroll the contents of the
Text Box right by one character, you set the wParam argument to SB_LINERIGHT.
Example Program
This program shows how you can scroll the contents of a Text Box control by using the
SendMessage function.
10. Add a Command Button control to Form1. Command1 is created by default. Set
its Caption property to "Left".
11. Add the following code to the Click event for Command1:
12. Private Sub Command1_Click()
13. Dim X As Long
14. X = SendMessage(Text1.hwnd, WM_HSCROLL, SB_LINELEFT, ByVal 0&)
15. End Sub
16. Add a second Command Button control to Form1. Command2 is created by
default. Set its Caption property to "Right".
17. Add the following code to the Click event for Command2:
18. Private Sub Command2_Click()
19. Dim X As Long
20. X = SendMessage(Text1.hwnd, WM_HSCROLL, SB_LINERIGHT, ByVal 0&)
21. End Sub
Run the example program by pressing F5. Type some text into the Text Box control.
Click the Left command button. The text scrolls to the left by one character position.
Click the Right command button. The text scrolls to the right by one character position.
Abstract
When developing an application in Microsoft® Visual Basic®, you may need to create a
temporary file on disk. This article explains how to create temporary files in Visual Basic
version 4.0.
Example Program
This program shows how to create a temporary file from within your Visual Basic
application.
1. Create a new project in Visual Basic. Form1 is created by default.
Abstract
The Text Box control in Microsoft® Visual Basic® lets your user type text that can later
be used within your program. Alternatively, you may want to display some text but do
not want the user to be able to edit that text. This article explains how to make a Text
Box control's contents read-only.
To use the SendMessage function within your program, include the following Declare
statement in the General Declarations section of your project (note that this Declare
statement must be typed as a single line of code):
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA"
(ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Integer,
ByVal lParam As Long) As Long
The SendMessage function requires four arguments, as follows.
hwnd A long value containing the handle of the Text Box control
wMsg A long value containing the message to be sent, in this case
EM_SETREADONLY
wParam An integer value set to True to set the control's read-only flag, or False to
remove the control's read-only flag
lParam A long value that should be set to zero (not used by EM_SETREADONLY)
After the program runs the SendMessage function, a long value is returned, indicating
success (if the value is nonzero) or false (if the value is zero).
Example Program
This program shows how to prevent a user from editing the contents of a Text Box
control without disabling the control itself.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that the Declare statement must be typed as a single line
of code):
3. Private Declare Function SendMessage Lib "user32" Alias "SendMessageA"
4. (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Integer,
5. ByVal lParam As Long) As Long
6. Const WM_USER = &H400
7. Const EM_SETREADONLY = (WM_USER + 31)
8. Add a Text Box control to Form1. Text1 is created by default. Set its MultiLine
property to True and its ScrollBars property to 3-Both.
Abstract
This article describes several undocumented keyboard and mouse features of Microsoft®
Visual Basic®.
• When designing an application, you can move a control's position within the form
up, down, left, or right by holding down CTRL while pressing the appropriate
arrow key.
• When designing an application, you can manually adjust the size of a control by
one pixel by holding down the SHIFT key while pressing the appropriate arrow
key.
• In the code window, pressing CTRL+SHIFT+F2 moves the cursor back to its
previous location.
• A context-sensitive menu is displayed for the toolbar, toolbox, form, control, code
window, debug window, and project window when you right-click that object.
Abstract
The Drive List Box control in Microsoft® Visual Basic® displays a list of all disk drives
attached to the computer system. This article explains how you can use the Microsoft
Windows® application programming interface (API) SendMessage function to remove a
selected drive entry from the Drive List Box control at run time in Visual Basic.
You can use the Drive List Box control to enable a user to easily switch to a different
disk drive. You do this by clicking a specific entry in the control. The current default disk
drive, however, is not actually changed—you must use the ChDir function to do this.
The Drive List Box control provides a simple method that you can employ to select the
actual disk drive. Typically, you would use the Drive List Box control in conjunction
with the File List Box control to create a file-access system of some sort.
The example program below shows how to remove the currently selected drive entry
from the Drive List Box control. You can accomplish this by using the Microsoft
Windows® application programming interface (API) SendMessage function to send a
CB_DELETESTRING message to that control.
First, however, you must determine which entry is currently selected in the Drive List
Box control. The ListIndex property of this control will return the index number of the
currently selected item. After you have retrieved this value, you use SendMessage to
send a CD_DELETESTRING message to the Drive List Box control. This message, in
turn, removes that specific entry from the control.
Example Program
This program shows how to remove a selected item from a Drive List Box control.
1. Create a new project in Visual Basic. Form1 is created by default.
10. Add the following code to the Click event for Command1:
11. Private Sub Command1_Click()
12. Dim X As Long
13. X = SendMessageAny(Drive1.hwnd, CB_DELETESTRING, Drive1.ListIndex, 0)
14. End Sub
Run the example program by pressing F5. Select one of the drive letters shown in the
Drive List Box control. Click the command button. The selected entry is removed from
the Drive List Box control.
Abstract
When you write a program in Visual Basic®, it may be necessary to temporarily enable
or disable the scroll bars in a List Box control. This article explains how to use the
Windows® application programming interface (API) GetSystemMetrics function with a
Picture Box control to enable or disable the scroll bars in a List Box control.
In a Visual Basic application, you can selectively enable or disable the scroll bars in a
List Box by first retrieving the width of the scroll bar's arrow bitmap. You do this by
calling the GetSystemMetrics function with the value SM_CXVSCROLL for the Index
argument. The width of the arrow bitmap is returned as a long value by the
GetSystemMetrics function.
Next, a Picture Box control must be positioned directly over the scroll bars on the
window or form in your project. The Width property of the Picture Box is set to the
width of the arrow bitmap. By setting the Visible property of the Picture Box control to
True, the user can employ the scroll bars in the usual manner. However, if you set the
Visible property of the Picture Box control to False, the user cannot see the scroll bars.
Therefore, the scroll bars become temporarily disabled.
Example Program
This program shows how to hide the scroll bars of a List Box control.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that the Declare statement must be typed as a single line
of code):
3. Const SM_CXVSCROLL% = 2
4. Private Declare Function GetSystemMetrics Lib "user32"
5. (ByVal nIndex As Long) As Long
AutoRedraw = True
BorderStyle = 0-None
Height = 450
Left = 2760
Top = 1800
Visible = False
Width = 1215
37. Add the following code to the Click event for Command1:
38. Private Sub Command1_Click()
39. ShowBar
40. End Sub
41. Add a second Command Button control to Form1. Command2 is created by
default. Set its Caption property to "Hide".
42. Add the following code to the Click event for Command2:
43. Private Sub Command2_Click()
44. HideBar
45. End Sub
Run the example program by pressing F5. Click the Hide command button. The scroll
bars on the List Box control are no longer visible, but you can still scroll through the
contents of the List Box with the arrow keys. Click the Show command button to show
the scroll bars on the List Box control.
Abstract
Each time you format a disk in MS-DOS®, you are given the opportunity to assign a
unique name (called a volume label) to that disk. This article explains how to retrieve a
disk's volume label in a Microsoft® Visual Basic® application.
You can use any of these numeric file attribute values in conjunction with the Dir$
function to retrieve specific types of files.
In the example program below, you want to display the volume label name for drive C.
To do this, you run the statement:
TempBuffer = Dir$("C:*.*", ATTR_VOLUME)
This tells Dir$ that you want to retrieve the file that has its volume label attribute set.
Because only one file on each disk can have a volume label at any given time, you need
to run this statement only once to retrieve the disk's name.
Example Program
This program shows how to retrieve a disk's volume label.
1. Create a new project in Visual Basic. Form1 is created by default.
Abstract
Within your Visual Basic® application, you can determine whether an attached drive is
actually a CD-ROM drive. This article explains how you can identify a CD-ROM drive
in Visual Basic.
Function 150Bh, Int 2Fh, tells you whether or not the specified disk drive is a valid CD-
ROM drive. To call this function, you set the AX register to 150Bh and the CX register to
the number of the disk drive you want to check. The function will return with the BX
register set to ADADh if the MSCDEX.EXE device driver (that is, the CD-ROM driver)
is installed, and the AX register is set to a nonzero value if the specified disk is a CD-
ROM drive. It is, therefore, simply a matter of testing each possible disk drive, from 0
through 25, to determine exactly how many CD-ROM drives are attached to the computer
system.
Example Program
This program tests each installed disk drive to determine whether it is a CD-ROM drive.
In addition, the drive letter of each CD-ROM drive is displayed in the Text Box along
with the total number of CD-ROM drives that the program found.
2. Add a Text Box control to Form1. Text1 is created by default. Set its MultiLine
property to True.
38. Add a new BAS module to your project. Copy the VBASM.TXT file to this new
BAS module.
Run the example program by pressing F5. Click the command button. In the Text Box
control, the program will display the drive letter of each CD-ROM drive found installed
in the computer system, in addition to a total count of the number of attached CD-ROM
drives.
Abstract
It's easy to write a procedure in Visual Basic to selectively find items in a List Box
control. For example, if you want to search the List Box control for the item "oranges,"
you can use a For-Next loop to check each entry in the List Box control to see whether it
matches the target string. To do this, use the following code:
For X = 0 To Lst.ListCount -1
If Lst.List(X) = "oranges" Then
'we found an item that matches.
End If
Next X
The code routine above tells us whether the item "oranges" was found in the List Box
control, but what happens if we want to find a partial item in the control? Let's suppose
that each item in the list contains a phrase such as "apples and oranges." You want to find
the item that contains the word "oranges." The above routine will only return a match if
the entire string matches the word "oranges."
To work around this problem, we can use the Visual Basic InStr function to parse each
entry in the List Box control. The InStr function will return the location within the larger
string where the target string is found. To use this search technique, you still need to
include a For-Next loop to examine each entry in the List Box control; however, you can
also add code to call the InStr function to determine whether a specific portion of an
entry matches your target string.
Each time the InStr function finds the target string in an entry in the List Box control, it
returns the target string's position within the entry. Just use the ListIndex property of the
List Box control to retrieve the entry that matches your target string.
Example Program
This program shows how to search a List Box control for a partially matching string.
1. Create a new project in Visual Basic. Form1 is created by default.
11. Add the following code to the Click event for Command1.
12. Private Sub Command1_Click()
13. GetPartialString
14. End Sub
15. Create a new procedure called GetPartialString. Add the following code to this
procedure.
16. Sub GetPartialString()
17. Dim LittleString As String
18. Dim Item As Integer
19.
20. LittleString = Text1.Text
21. Item = GetMatch(List1, LittleString)
22.
23. If Item = -1 Then
24. MsgBox "No such entry found in List Box"
25. Else
26. List1.ListIndex = Item%
27. End If
28. End Sub
29. Create a new procedure called GetMatch. Add the following code to this
procedure.
30. Function GetMatch(Lst As ListBox, ByVal SearchStr As String) As Integer
31. Dim X As Integer
32.
33. For X = 0 To Lst.ListCount - 1
34. If InStr(Lst.List(X), SearchStr) Then
35. GetMatch = X
36. Exit Function
37. End If
38. Next X
39.
40. GetMatch = -1 'no match
41. End Function
Run the demonstration program by pressing F5. Three items are displayed in the List
Box control. Type a word such as "corn" in the Text Box control and click the command
button. The program highlights the "Peaches and corn" entry in the List Box control
because the word "corn" was found in this entry. Type the word "turnip" in the Text Box
control. After you click the command button, a message box is displayed that tells you no
such item was found.
Abstract
While developing an application in Microsoft® Visual Basic®, you may need to allow
your user to use long file names. This article explains how you can determine whether the
operating system supports long file names.
After the program calls the GetVolumeInformation function, a value of True is returned
if the function was successful and all information about the disk/file system was
retrieved. A value of False is returned if the function was not successful.
After you have executed the GetVolumeInformation function, it returns the maximum
component length of a file name. An ordinary MS-DOS® file name (such as
COMMAND.COM) consists of eight characters followed by three characters. In this
case, the value returned by GetVolumeInformation would be 8.3. If the operating
system supports long file names, the value returned will be 255, regardless of the actual
length of the file name.
Example Program
This program shows how you can retrieve the volume name of a disk, and how to
determine whether the operating system supports long file names.
10. Add a second Text Box control to Form1. Text2 is created by default.
12. Add the following code to the Click event for Command1.
Abstract
The Microsoft® Windows® 95 taskbar allows you to easily launch Windows-based
programs and to determine which applications are currently running. The taskbar can also
display status information, such as the current time. This article will explain how you can
determine, from within a Visual Basic® program, whether the taskbar is visible or
hidden.
After we have called the SHAppBarMessage function, a value is returned indicating the
state of the taskbar. If this value is zero, we know the taskbar is not in autohide mode or
always-on-top mode. If the value returned is &H1, the taskbar is in autohide mode; if the
value returned is &H2, the taskbar is in always-on-top mode.
Example Program
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that the Declare statement must be typed as a single line
of code):
3. Private Declare Function SHAppBarMessage Lib "shell32.dll"
4. (ByVal dwMessage As Long, pData As APPBARDATA) As Long
5. Const ABS_ALWAYSONTOP = &H2
6. Const ABS_AUTOHIDE = &H1
7. Const ABM_GETSTATE = &H4
8. Add a Command Button control to Form1. Command1 is created by default.
Abstract
The TabStrip control in Microsoft® Visual Basic® does not provide built-in support for
using accelerator keys. This article explains how you can add this functionality to your
Visual Basic application.
The user can select a tab either by pressing the TAB key to move the focus to the next tab
or by clicking the desired tab. Although there is no direct support provided when using
the TabStrip control, you can add accelerator keys to the TabStrip control. This will
allow your user to switch the focus between tabs by pressing and holding down the ALT
key and then pressing another key.
In the demonstration program below, the TabStrip control displays three tabs: Control,
Settings, and Parameters. Notice that an ampersand ("&") has been used in the tabs'
Caption property. At run time, the character immediately following the ampersand will
be underlined. In the example program, the Control tab will be shown with the letter "C"
underlined. Under the Microsoft Windows® operating system, the underlined character
tells users that they can press the underlined character while holding down the ALT key
Example Program
This program shows how to add support for accelerator keys to the Visual Basic
TabStrip control.
1. Create a new project in Visual Basic. Form1 is created by default. Set its
KeyPreview property to True.
Run the example program by pressing F5. The TabStrip control is displayed with three
tabs set—one for Control, one for Settings, and one for Parameters. You can move the
focus from one tab to another by pressing and holding down the ALT key and then
pressing the appropriate accelerator key (the underlined character) for the new tab.
Abstract
The Rich-Text Box control allows you to create rich-text format (RTF) documents from
within your Microsoft® Visual Basic® application. However, when you want to insert a
tab character in the Rich-Text Box control, the focus is instead moved to the next control
in the tab order specified by the TabIndex property. This article explains how you can
insert the tab character into the Rich-Text Box control itself.
Example Program
This program shows how to insert a tab control character in the Rich-Text Box control in
Visual Basic version 4.0.
1. Create a new project in Visual Basic. Form1 is created by default.
Abstract
Microsoft® Windows® 95 uses the registry to determine which applications and
hardware items are installed in the computer system. This article explains how you can
retrieve the name of the default printer from the registry from within a Visual Basic®
application.
You also need to tell the RegOpenKeyEx function that you want to work with the
Default subkey. After the program calls this function, a value that is set to zero is
returned if the function was successful.
The next step is to retrieve the actual value stored for the key that you are interrogating.
Because you want to retrieve the name that is assigned to the default printer, you should
call the RegQueryValueEx function. You must tell this function that you want to
retrieve the value that was given to the Default subkey.
Finally, you must call the RegCloseKey function to release the handle of the key that you
have been accessing in the registration database. This terminates access to the registration
database and frees the handle for future use by the computer system.
Example Program
This program shows how to retrieve the name of the default printer from the Windows 95
registry.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that each Declare statement must be typed as a single line
of code):
3. Private Declare Function RegOpenKeyEx Lib "advapi32" Alias "RegOpenKeyExA"
4. (ByVal hKey As Long, ByVal lpSubKey As String, ByVal dwReserved As Long,
5. ByVal samDesired As Long, phkResult As Long) As Long
6. Private Declare Function RegQueryValueEx Lib "advapi32" Alias "RegQueryValueExA"
7. (ByVal hKey As Long, ByVal lpValueName$, ByVal lpdwReserved As Long, lpdwType
8. As Long, lpData As Any, lpcbData As Long) As Long
9. Private Declare Function RegCloseKey Lib "advapi32" (ByVal hKey As Long) As Long
10. Const HKEY_CURRENT_CONFIG As Long = &H80000005
11. Add a Text Box control to Form1. Text1 is created by default.
13. Add the following code to the Click event for Command1.
14. Private Sub Command1_Click()
15. Dim PName As String
16. PName = GetCurrPrinter()
17. Text1.Text = PName
18. End Sub
Abstract
The Common Dialog File control lets you easily select one or more files in your
Microsoft® Visual Basic® application. This article shows how you can retrieve the
names of selected files from the Common Dialog control.
To enable your Visual Basic program to work with files selected by the user, you need to
retrieve each file name from the control's Filename property. The file names selected by
the user are all stored in this property as one long string. Each file name is separated by a
space (32) character.
You can use the InStr function to search for the delimiting space character to retrieve
each file name from the Filename property of the Common Dialog. The InStr function
returns the location of the space character within the Filename property string. After you
have obtained the location of the space character, you can use the Mid function to
remove the individual file name entry from the string.
Example Program
This program shows how to retrieve all file names selected in a Common Dialog File
control.
1. Create a new project in Visual Basic. Form1 is created by default.
4. Add a second Text Box control to Form1. Text2 is created by default. Set its
MultiLine property to True.
Abstract
Microsoft® Word for Windows® includes a spelling checker that you can invoke from
within your Microsoft Visual Basic® application. This article shows how you can use
OLE Automation in a Visual Basic program to check the spelling of text.
In the example program below, the contents of the Text Box control need to be checked
for spelling. To do this, you execute a CreateObject statement to tell Microsoft
Windows to run Microsoft Word. Next, you need to tell Word to create a new document
and to copy the text from the Text Box to this document. You accomplish both of these
functions by running the WordBasic FileNew and Insert commands, respectively.
After the text has been copied to the Word document, it can be checked for spelling. You
run the ToolsSpelling command in Microsoft Word to start the spelling checker.
When you have finished checking the document for spelling errors, click the OK
command button to close the spelling checker in Microsoft Word. Then, run the
EditSelectAll and FileExit commands to copy the newly revised text back to your Visual
Basic Text Box, which ends the OLE Automation process.
Example Program
This program shows how to use the spelling checker in Microsoft Word from within a
Visual Basic application.
2. Add a Text Box control to Form1. Text1 is created by default. Set its MultiLine
property to True.
Abstract
When you write a program in Microsoft® Visual Basic®, you may need to determine
which disk drives are installed in the computer system. This article shows how to
enumerate all disk drives within Visual Basic version 4.0.
After the program calls this function, the lpBuffer is filled with entries that describe each
valid disk drive found in the computer system. The string is null-terminated. Each entry
in this string contains the drive letter, followed by a colon and a backslash character. For
example, if drive A is found, the string will contain the entry:
NULL a:\ NULL NULL
Notice that each entry is terminated by a null byte, and the last entry in the string is
terminated by two consecutive null bytes.
The example program below displays a list of all available disk drives in the Text Box
control. The program uses the InStr and Mid functions to extract each individual entry
from the lpBuffer string.
Example Program
This program shows how to create a list of all disk drives installed in the computer
system.
1. Create a new project in Visual Basic. Form1 is created by default.
Text1.Text = ""
X = GetLogicalDriveStrings(BufLen, BufString)
On Error GoTo Quit_Now
Do
X=Y+1
Z=Z+1
Y = InStr(X, BufString, "\")
Quit_Now:
End Sub
Run the example program by pressing F5. Click the OK command button. The Text Box
will contain a list of all available disk drives in the computer system.
Abstract
The List Box control in Microsoft® Visual Basic® allows you to display a list of items
to the user of your program. When you design a List Box control in a Visual Basic
program, you can use the Microsoft Windows® application programming interface (API)
SendMessage function to determine the size of individual items in the control. This
article explains how you can calculate the number of items that can be displayed in the
control, based on the size of each entry.
Example Program
This program shows how to calculate the number of items that can be displayed in a List
Box control.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that the Declare statement must be typed as a single line
of code):
3. Private Declare Function SendMessage Lib "user32" Alias "SendMessageA"
4. (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Integer,
5. ByVal lParam As Long) As Long
6. Const LB_GETITEMHEIGHT = &H1A1
7. Add the following code to the Form_Load event for Form1 (note that the Items =
line must be typed as a single line of code):
8. Private Sub Form_Load()
9. Dim ItemHeight As Long
10. Dim Items As Integer
11.
12. ItemHeight = SendMessage(List1.hwnd, LB_GETITEMHEIGHT, 0, 0&)
13. Items = (List1.Height - 2 * Screen.TwipsPerPixelY)
14. / (Screen.TwipsPerPixelY * ItemHeight)
15. Text1.Text = "Maximum # entries : " & Str(Items)
16.
17. List1.AddItem "Item #1"
18. List1.AddItem "Item #2"
19. List1.AddItem "Item #3"
20.
21. End Sub
22. Add a Text Box control to Form1. Text1 is created by default.
25. Add the following code to the Click event for Command1 (note that the Items =
line must be typed as a single line of code):
26. Private Sub Command1_Click()
27. Dim ItemHeight As Long
28. Dim Items As Integer
29. Dim X As Integer
30.
31. ItemHeight = SendMessage(List1.hwnd, LB_GETITEMHEIGHT, 0, 0&)
32. Items = (List1.Height - 2 * Screen.TwipsPerPixelY)
Abstract
When you design a Microsoft® Visual Basic® application, you can add a Text Box
control to your project. The Text Box control lets a user type text that can be manipulated
by your program. This article explains how you can add a word-search function to your
program.
It is a simple task to direct the InStr function to search for a particular word in the Text
Box control. Let's assume you want to see whether the word dog is in the string, "He
owns a cat and a dog". To do this, you tell InStr to search for the target word by issuing a
statement such as:
Example Program
This program shows how to search a Text Box control for whole words.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add a Text Box control to Form1. Text1 is created by default. Set its MultiLine
property to True.
3. Add a Label control to Form1. Label1 is created by default. Set its Caption
property to "Find word:".
Abstract
Within a Microsoft® Visual Basic® application, you can determine the status of any
virtual key on the keyboard. This article explains how to retrieve and set the status of
virtual keys.
When you want to turn the NUM LOCK key on, you set its status to 1. Alternatively, if
you want to toggle the NUM LOCK key off, you set its status to 0.
The final step is to tell the operating system that you have changed the status of a virtual
key on the keyboard. You do this by calling the SetKeyboardState function, which
copies the new keyboard status array to the operating system. When the program carries
out this function, the status of the NUM LOCK key is immediately changed.
Example Program
This program shows how to turn the NUM LOCK key on and off.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that each Declare statement must be typed as a single line
of code):
3. Private Declare Sub GetKeyboardStateByString Lib "user32" Alias
4. "GetKeyboardState" (ByVal pbKeyState As String)
5. Private Declare Sub SetKeyboardStateByString Lib "user32" Alias
6. "SetKeyboardState" (ByVal lppbKeyState As String)
7. Const VK_NUMLOCK = &H90
8. Add a Command Button control to Form1. Command1 is created by default. Set
its Caption property to "On".
18. Add the following code to the Click event for Command2:
19. Private Sub Command2_Click()
20. Dim NumLockKey As String * 256
21. NumLockKey = Space$(256)
22. GetKeyboardStateByString (NumLockKey)
23. Mid$(NumLockKey, VK_NUMLOCK + 1, 1) = Chr$(0)
24. Call SetKeyboardStateByString(NumLockKey)
25. End Sub
Run the example program by pressing F5. Click the On command button to turn on the
NUM LOCK key. Click the Off command button to turn off the NUM LOCK key.
Abstract
The MS-DOS® PATH statement tells the operating system to look for files in specific
directories on your disk. This article explains how to find out whether a specific file
exists in one of the PATH directories.
The first step is to retrieve the entire path for the specified disk drive. The Visual Basic
CurDir$ function returns the current disk drive's path.
Next, you need to call two Microsoft Windows® application programming interface
(API) functions, GetWindowsDirectory and GetSystemDirectory. The
GetWindowsDirectory function retrieves the path of the Windows directory. Windows
Example Program
This program shows how to determine whether a specific file exists in one of the
directories in the PATH statement.
1. Create a new project in Visual Basic. Form1 is created by default.
11. Add the following code to the Click event for Command1:
12. Private Sub Command1_Click()
13. Dim DirStr As String
14. Dim FileToFind As String
15. Dim Flag As Integer
16.
17. FileToFind = Text1.Text
18. Flag = IsFileInPath(FileToFind, DirStr)
19. If Flag Then
20. MsgBox "File Exists in: " & DirStr
21. Else
22. MsgBox "File does not exist in PATH"
23. End If
24. End Sub
25. Create a new function called BuildSearchPath. Add the following code to this
function:
26. Sub BuildSearchPath(PathStr As String)
27. Dim RetVal As Integer
28. Dim Buffer As String * 128
29.
30. PathStr = CurDir$
Abstract
In a Microsoft® Visual Basic® program, you can use a Microsoft Windows® application
programming interface (API) function to reboot the computer system in various ways.
This article explains how to quit Windows 95 and shut down the computer system.
In the example program below, you use a combination of three of the above flags. This
flag combination (EWX_LOGOFF, EWX_FORCE, and EWX_REBOOT) tells Windows
95 to quit all currently executing processes, log the user off network connections, and
leave the computer system ready for the user to turn off.
Example Program
This program shows how to shut down the computer system.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that the Declare statement must be typed as a single line
of code):
3. Private Declare Function ExitWindowsEx Lib "user32" (ByVal uFlags As Long,
4. ByVal dwReserved As Long) As Long
5. Const EWX_LOGOFF = 0
6. Const EWX_SHUTDOWN = 1
7. Const EWX_REBOOT = 2
8. Const EWX_FORCE = 4
9. Const EWX_POWEROFF = 8
10. Const EWX_RESET = EWX_LOGOFF + EWX_FORCE + EWX_REBOOT
11. Add a Command Button control to Form1. Command1 is created by default.
Abstract
This article explains how to scroll text horizontally within a Picture Box control in
Microsoft® Visual Basic®.
Example Program
This program shows how to scroll text horizontally in a Picture Box control.
1. Create a new project in Visual Basic. Form1 is created by default.
Abstract
The Microsoft® Windows® 95 taskbar allows you to quickly switch between
applications, launch other applications by using the Start button, and perform many other
similar tasks. When developing your own Microsoft Visual Basic® applications, you can
also add new icons (that is, programs) to the Windows 95 taskbar. This article explains
how you can add icons to and remove icons from the notification area of the Windows 95
taskbar.
It's easy to add a new icon to the taskbar. The example program below shows how to add
a new icon to the taskbar, perform functions relevant to that new icon, and then remove
the icon from the taskbar. All this functionality is accomplished by using the
Shell_NotifyIcon function. You can use the Shell_NotifyIcon function in a Visual Basic
application to modify the Windows 95 taskbar. To use this function, you must include the
following Declare statement in the General Declarations section of your form:
Declare Function Shell_NotifyIcon Lib "shell32.dll" Alias "Shell_NotifyIconA"
(ByVal dwMessage As Long, lpData As NOTIFYICONDATA) As Long
The Shell_NotifyIcon function requires only two arguments. The first argument is one of
the following three messages you want to send to the Windows 95 taskbar:
NIM_ADD Add a new icon to the taskbar.
NIM_DELETE Remove (delete) an icon from the taskbar.
NIM_MODIFY Modify an existing icon on the taskbar.
In each case, either a True value is returned if the message was executed successfully or a
False value is returned if an error occurred in the attempt to process the message.
The second argument required by the Shell_NotifyIcon function is the address of a
NOTIFYICONDATA structure. This structure contains the information used by the
Shell_NotifyIcon function to modify the taskbar as specified. This structure must be
defined as follows:
Type NOTIFYICONDATA
cbSize As Long
hwnd As Long
uID As Long
uFlags As Long
uCallbackMessage As Long
hIcon As Long
szTip As String * pnTOOLTIP_SZ
End Type
where:
cbSize The size of the NOTIFYICONDATA structure itself.
hWnd The handle of the window that will receive the notification
messages associated with an icon on the taskbar.
wID An application-defined identifier of the taskbar icon.
When a mouse event occurs over the icon, the identifier is used for notification messages
sent to the hWnd window:
hIcon The handle of the taskbar icon
szTip The text for the taskbar icon's tooltip
Note that the Shell_NotifyIcon function is used to send a particular message to the
system. The individual message you send to the taskbar adds a new icon, deletes an
existing icon, or modifies an existing icon.
You can add a new icon to the Windows 95 taskbar by sending a NIM_ADD message.
The newly added icon appears on either the right side or the bottom of the toolbar. If the
Show Clock option of the taskbar is selected, the new taskbar icon is set to the immediate
left of the Clock applet icon. Each time you add a new icon to the taskbar, any and all
existing taskbar icons are shifted one position to the left.
Alternatively, when you want to remove an icon from the taskbar, you send a
NIM_DELETE message to your window. You do not need to modify the contents of the
NOTIFYICONDATA structure because that structure already contains the data used by
the program to add the new icon to the taskbar. After the NIM_DELETE message is
processed by the system, the icon is removed from the taskbar.
Example Program
This program shows how to add a new icon to the Windows 95 taskbar. In addition, it
shows how to remove the newly added icon and to receive callback messages, using the
Message Blaster custom control, from the new taskbar icon.
1. Create a new project in Visual Basic. Form1 is created by default.
11. Add the following code to the MessageBlaster1_Message event (note that the
Private statement must be typed as a single line of code):
12. Private Sub MessageBlaster1_Message(ByVal hwnd As Long, ByVal Msg As Long,
13. wParam As Long, lParam As Long, nPassage As Integer, lReturnValue As Long)
14. On Error Resume Next
15. Select Case lParam
16. Case WM_LBUTTONDOWN
17. MsgBox "My Little App is running!", , App.Title
18. Case WM_RBUTTONDOWN
19. PopupMenu mnuMain, 0, , , mnuClose
20. Case WM_USER + 1
21. End
22. End Select
23. End Sub
24. From the Visual Basic Tools menu, select Menu Editor. Create a menu with the
following items:
Caption: &Main
Name: mnuMain
Caption: &Date
Name: mnuDate
Caption: &Time
Name: mnuTime
Caption: &Close
Name: mnuClose
25. Add the following code to the Click event for mnuClose:
26. Private Sub mnuClose_Click()
27. On Error Resume Next
28. DeleteOldIcon
29. SendMessage hwnd, WM_USER, 0, WM_USER + 1
30. End Sub
31. Add the following code to the Click event for mnuDate:
32. Private Sub mnuDate_Click()
33. MsgBox "Today is: " & Date, , App.Title
40. Add the following code to Module1.Bas (note that the Declare statement must be
typed as a single line of code):
41. Option Explicit
42.
43. Declare Function Shell_NotifyIcon Lib "shell32.dll" Alias "Shell_NotifyIconA"
44. (ByVal dwMessage As Long, lpData As NOTIFYICONDATA) As Long
45. Public Const NIF_ICON = &H2
46. Public Const NIF_MESSAGE = &H1
47. Public Const NIF_TIP = &H4
48. Public Const NIM_ADD = &H0
49. Public Const NIM_DELETE = &H2
50. Public Const MyToolTip As Integer = 64
51.
52. Type NOTIFYICONDATA
53. cbSize As Long
54. hWnd As Long
55. uID As Long
56. uFlags As Long
57. uCallbackMessage As Long
58. hIcon As Long
59. szTip As String * MyToolTip
60. End Type
61.
62. Public NewIcon As NOTIFYICONDATA
63. Create a new subroutine called CreateNewIcon. Add the following code to this
subroutine:
64. Sub CreateNewIcon(OurWindow As Object, OurMsg As Long, OurToolTip As String)
65. On Error Resume Next
66. Dim X As Long
67. NewIcon.uFlags = NIF_ICON Or NIF_TIP Or NIF_MESSAGE
68. NewIcon.szTip = OurToolTip & Chr$(0)
69. NewIcon.hWnd = OurWindow.hWnd
70. NewIcon.uID = OurWindow.Icon
71. NewIcon.uCallbackMessage = OurMsg
72. NewIcon.hIcon = OurWindow.Icon
73. NewIcon.cbSize = Len(NewIcon)
74. X = Shell_NotifyIcon(NIM_ADD, NewIcon)
75. End Sub
76. Create a new subroutine called DeleteIcon. Add the following code to this
subroutine:
77. Sub DeleteOldIcon()
78. On Error Resume Next
Abstract
This article explains how to center forms on the screen in your Microsoft® Visual
Basic® application.
Once you have calculated where on the screen the form should be placed, you use the
Move method to position the form in the center of the screen.
Example Program
This program shows how to center a form on the screen.
Abstract
The Microsoft® Windows® directory contains such files as Windows-based application
files, initialization files, and Help files. This article explains how to retrieve the path of
the Windows directory from within your Microsoft Visual Basic® application.
Example Program
This program shows how to retrieve the path of the Windows directory.
1. Create a new project in Visual Basic. Form1 is created by default.
Abstract
In your Microsoft® Visual Basic® application, you can establish the absolute minimum
size for a form. This article explains how to allow a user to resize a form only if the form
is larger than the minimum size.
If the current height or width of the form is greater than the minimum size, you allow the
form to be resized. On the other hand, if the user tries to shrink the form's size to a much
smaller size, you prevent the change from taking place.
Example Program
Height = 2250
Left = 1260
Top = 1965
Width = 4515
3. Add the following code to the Form_Resize event for Form1:
4. Private Sub Form_Resize()
5. MIN_WIDTH = 4515
6. MIN_HEIGHT = 2250
7. If WindowState <> 1 Then
8. If Width < MIN_WIDTH Then Width = MIN_WIDTH
9. If Height < MIN_HEIGHT Then Height = MIN_HEIGHT
10. End If
11. End Sub
Run the example program by pressing F5. When you try to change the size of Form1 to
make it smaller, the code in the Resize event prevents the form's size from changing. You
can make the form larger, but not smaller.
Abstract
This article explains how to retrieve the version numbers of MS-DOS® and/or the
Microsoft® Windows® operating system installed on your computer system.
Example Program
This program shows how to retrieve the version of MS-DOS and Windows installed in
the computer system.
26. Add a second Text Box control to Form1. Text2 is created by default.
27. Create a new function called GetHiLoByte. Add the following code to this
function:
28. Sub GetHiLoByte(X As Integer, LoByte As Integer, HiByte As Integer)
29. LoByte = X And &HFF&
Abstract
The Microsoft® Visual Basic® Common Dialog control allows you to display a Save As
dialog box in your Visual Basic application so that a user can save a file to disk. This
article explains how to prevent a user from saving files to a disk drive that is not installed
on the computer system.
You can require that a user save the file to a specific disk drive by first testing for a drive
designation. The name of the file the user types is stored in the Common Dialog control's
Filename property. It is a simple matter to check the first letter of this string to determine
which disk drive the user wants to save the file to. You can then modify the drive
designation to suit your needs.
Example Program
This program shows how to force the Common Dialog Save As dialog box to save a file
to a specific disk drive.
1. Create a new project in Visual Basic. Form1 is created by default.
9. Create a new function called Save_DriveA. Add the following code to this
function:
10. Function Save_DriveA()
11. Dim X As Integer
12.
13. Do
14. CommonDialog1.Action = 2 'save file
15. If UCase(Left(CommonDialog1.filename, 1)) <> "A" Then
16. MsgBox "You must save file to drive A only"
17. Else
18. Exit Do
19. End If
20. DoEvents
21. Loop
22.
23. X = FreeFile
24. Open CommonDialog1.filename For Output As #X
25. Print #X, Text1.Text
26. Close #X
27. MsgBox "File has been saved to drive A"
28.
29. End Function
Run the example program by pressing F5. Click the Command Button control. The
Common Dialog Save As dialog box appears on the screen. Type the name you want to
assign to the file, and click the Save button. If you specified a disk drive other than drive
Abstract
This article explains how to determine whether a file exists on a disk drive in a
Microsoft® Visual Basic® application.
The third argument, wStyle, tells the OpenFile function the action that the function is to
perform. Because you want to find out whether a given file exists, you call the OpenFile
function with the wStyle argument set to OF_EXIST. If the file does not exist, the
OpenFile function will return an error code of 2—File Not Found.
When the OpenFile function is run, it writes information about the file to the
OFSTRUCT structure. Therefore, if an error occurs, you must retrieve the actual error
code from the OFSTRUCT structure itself. In the example program below, you use the
statement:
If OpenFileStructure.nErrCode = FILE_NOT_FOUND Then
After testing for the "File Not Found" error, you can indicate to the user whether or not
the file exists.
Example Program
This program shows how to determine whether a file already exists on the disk drive.
1. Create a new project in Visual Basic. Form1 is created by default.
Abstract
This article explains how to allow the user of your Microsoft® Visual Basic® application
use the ENTER key, instead of double-clicking with the mouse, to select a directory.
You may, however, want to select a directory from the Directory List Box control by
pressing the ENTER key instead of double-clicking with the mouse. This functionality
can be accomplished by monitoring the KeyPress event of the Directory List Box
control.
Whenever a key is pressed on the keyboard, a KeyPress event is triggered in the control
that has the focus. A special number representing that particular key is stored in the
KeyPress event's KeyAscii variable. You can then test the KeyAscii variable to determine
whether a specific key, such as ENTER, was pressed on the keyboard.
In the example program below, each time a KeyPress event is triggered, the focus is set to
the Directory List Box control. The KeyAscii variable is then tested to determine
whether ENTER (represented by the number 13) was pressed. Next, a
WM_LBUTTONDBLCLK (double-click) message is sent to the Directory List Box
control by using the Microsoft Windows® application programming interface (API)
SendMessage function. The KeyAscii variable is then set to a value of zero, which
prevents the beep from being played on the computer's speaker. Finally, the default
directory is changed to the newly selected directory.
Example Program
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that each statement must be typed as a single line of code):
3. Private Declare Function GetFocus Lib "user32" () As Long
4. Private Declare Function SendMessage Lib "user32" Alias "SendMessageA"
5. (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Integer,
6. ByVal lParam As Long) As Long
7. Const WM_LBUTTONDBLCLK = &H203
8. Add the following code to the Form_Load event for Form1:
9. Private Sub Form_Load()
10. Text1.Text = ""
11. Text1.Text = CurDir$
12. End Sub
13. Add a Text Box control to Form1. Text1 is created by default.
14. Add a Directory List Box control to Form1. Dir1 is created by default.
15. Add the following code to the Dir1_KeyPress event for Dir1:
16. Private Sub Dir1_KeyPress(KeyAscii As Integer)
17. Dim R As Long
18. Dim DirHwnd As Integer
19. Dim X As String
20. If KeyAscii = 13 Then
21. Dir1.SetFocus
22. DirHwnd = GetFocus()
23. R = SendMessage(DirHwnd, WM_LBUTTONDBLCLK, 0, 0)
24. KeyAscii = 0
25. End If
26. X = Dir1.Path
27. ChDir X
28. Text1.Text = CurDir$
29. End Sub
Run the example program by pressing F5. The Directory List Box control displays a list
of directories found on your hard drive. The name of the default directory appears in the
Text Box control.
Select a directory from the Directory List Box control by pressing the first letter of the
directory name or by clicking the directory name. Press ENTER. The currently selected
directory is now the default directory.
Abstract
This article explains how to copy files from one directory to another in a Microsoft®
Visual Basic® application.
Unfortunately, the FileCopy statement does not allow you to specify a wildcard source
filename. Using MS-DOS®, you could copy a group of files by issuing a command such
as:
COPY *.* C:\NEWFILES
This command tells MS-DOS to copy all the files in the current directory to the
NEWFILES directory on drive C.
To accomplish this same task in Visual Basic, you must use the Dir$ function to retrieve
the name of each individual file in the source directory. Then you use the FileCopy
statement to copy that individual file to the target directory.
A While-Wend routine can be used to quickly retrieve the names of all files in the target
directory. As shown in the CopyFile subroutine in the example program below, the Dir$
function returns the name of each file it finds. When Dir$ returns an empty text string
(""), you know that all files have been processed.
Example Program
This program shows how to copy all files from the source directory to the destination
directory.
1. Create a new project in Visual Basic. Form1 is created by default.
9. Add a Text Box control to Form1. Text1 is created by default. Position the Text
Box control so that it is directly adjacent to the first Label control.
10. Add a second Text Box control to Form1. Text2 is created by default. Position the
Text Box control so that it is directly adjacent to the second Label control.
11. Add a Command Button control to Form1. Command1 is created by default. Set
its Caption property to "Copy Files".
12. Add the following code to the Click event for Command1:
13. Private Sub Command1_Click()
14. Dim SourceDir As String
15. Dim TargetDir As String
16. Dim X As Integer
17. Dim P As Integer
18.
19. SourceDir = text1.Text
20. TargetDir = text2.Text
21. CopyFile SourceDir, TargetDir, P
22. MsgBox "Number of files copied = " & Str$(P)
23. End Sub
24. Create a new subroutine called CopyFile. Add the following code to this
subroutine:
25. Sub CopyFile(SrcDir As String, TrgtDir As String, NumFiles As Integer)
26. Dim OldDir As String 'source dir name
27. Dim NewDir As String 'target dir name
28. Dim FileName As String 'source filename
29. Dim sType As String 'file type (extension)
30.
31. OldDir = SrcDir
32. If Right$(OldDir, 1) <> "\" Then
33. OldDir = OldDir & "\"
34. End If
35.
36. NewDir = TrgtDir
37. If Right$(NewDir, 1) <> "\" Then
38. NewDir = NewDir & "\"
39. End If
40.
41. NumFiles = 0 'returns # files copied
42.
43. FileName = Dir$(OldDir & "*.*")
44. While FileName <> ""
45. On Error Resume Next
46. FileCopy (OldDir & FileName), (NewDir & FileName)
47. If Err = 0 Then
Abstract
In a Microsoft® Visual Basic® application, you may need to determine what types of
disk drives are installed on a computer system. This article explains how to locate the
CD-ROM drives that are installed.
As you know, all disk drives are identified by an alphabetic letter, starting with the letter
A. The ASCII value for the letter A is 65. Because there are 26 possible disk drives, you
can use a For-Next loop to test each possible disk drive to determine whether it is a CD-
ROM disk drive.
Example Program
This program shows how to locate all CD-ROM disk drives installed on the computer
system.
1. Create a new project in Visual Basic. Form1 is created by default.
11. Create a new function called FindCDROM. Add the following code to this
function:
12. Function FindCDROM() As String
13. Dim Drive As Integer
14. Const DRIVE_CDROM = 5
15. FindCDROM = "No CD_ROM Installed"
16.
17. For Drive = 65 To 90
18. If GetDriveType(Chr(Drive) & ":\") = DRIVE_CDROM Then
19. FindCDROM = "CD-ROM Drive " & Chr(Drive) & ":\"
Abstract
This article explains how to play a waveform-audio (.WAV) file in your Microsoft®
Visual Basic® application.
Example Program
This program shows how to play a .WAV file in Visual Basic.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that each statement must be typed as a single line of code):
3. Private Declare Function sndPlaySound Lib "winmm.dll" Alias "sndPlaySoundA"
4. (ByVal lpszSoundName As String, ByVal uFlags As Long) As Long
5. Const SND_SYNC = &H0 ' play synchronously (default)
6. Const SND_NODEFAULT = &H2 ' silence not default, if sound not found
7. Add a Command Button control to Form1. Command1 is created by default.
Abstract
This article explains how to control the state of any virtual key from within a Microsoft®
Visual Basic® application.
To isolate the CAPS LOCK and NUM LOCK keys, you must interrogate the bytes stored
in the KeyboardBuffer array. The constants VK_CAPITAL and VK_NUMLOCK
represent the CAPS LOCK and NUM LOCK keys, respectively. If the low-order bit in
the byte representing the toggle key is 1, then the key is on. If the low-order bit is 0, the
key is off.
You can use the Visual Basic logical AND operator to test the low-order bit for the toggle
keys, as shown here:
If KeyboardBuffer(VK_CAPITAL) And 1 Then
KeyboardBuffer(VK_CAPITAL) = 0
Else
KeyboardBuffer(VK_CAPITAL) = 1
End If
In the code fragment above, you first test the state of the CAPS LOCK key. If the CAPS
LOCK key is currently on (the low-order bit is 1), you reset the low-order bit to 0 to turn
the key off. If the CAPS LOCK key is off (the low-order bit is 0), you reset the low-order
bit to 1 to turn the key on.
When you want to reverse the state of the toggle keys (that is, turn the key on if it is not
engaged or off if it is engaged), you use the SetKeyboardState function. This function
modifies the state of any virtual key. The key you want to modify is again stored in the
KeyboardBuffer array.
Example Program
This program shows how to turn the toggle (CAPS LOCK and NUM LOCK) keys on and
off.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1:
3. Private Declare Sub GetKeyboardState Lib "user32" (lpKeyState As Any)
4. Private Declare Sub SetKeyboardState Lib "user32" (lpKeyState As Any)
5. Const VK_CAPITAL = &H14
6. Const VK_NUMLOCK = &H90
7. Add a Command Button control to Form1. Command1 is created by default.
Abstract
This article explains how to print a file specified by the user of your Microsoft Visual
Basic® application.
To use the ShellExecute function, you must include the following Declare statement in
your project:
Private Declare Function ShellExecuteAny Lib "shell32.dll" Alias "ShellExecuteA"
(ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String,
ByVal lpParameters As Any, ByVal lpDirectory As Any, ByVal nShowCmd As Long)
As Long
The ShellExecute function requires six arguments, as follows:
Example Program
This program shows how to use the ShellExecute function to print a Microsoft Word
document. The function can also print regular text files, such as those created by the
Windows 95 Notepad application.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that the Declare statement must be typed as a single line
of code):
3. Private Declare Function ShellExecuteAny Lib "shell32.dll" Alias "ShellExecuteA"
4. (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String,
5. ByVal lpParameters As Any, ByVal lpDirectory As Any, ByVal nShowCmd As Long)
6. As Long
7. Const SW_SHOWMINNOACTIVE = 7
8. Add the following code to the Form_Load event for Form1:
9. Private Sub Form_Load()
10. Text1.Text = ""
11. End Sub
12. Add a Text Box control to Form1. Text1 is created by default.
13. Add a Command Button control to Form1. Command1 is created by default. Set
its Caption property to "Print".
14. Add the following code to the Click event for Command1 (note that the "Ret ="
statement must be typed as a single line of code):
15. Private Sub Command1_Click()
16. Dim Ret As Long
17. Dim FileToPrint As String
18.
19. FileToPrint = Text1.Text
20. Ret = ShellExecuteAny(Me.hwnd, "print", FileToPrint, ByVal 0&, ByVal 0&,
21. SW_SHOWMINNOACTIVE)
22. End Sub
Run the example program by pressing F5. Type the name of a Microsoft Word document
or text file you want to print in the Text Box control. Click the Print command button to
run the application that originally created the document or text file. Notice that this
Abstract
This article explains how to set Microsoft® Windows® Help files (or the Help files of
any other application) to a specific position on the screen and to a specific size.
The WinHelp function runs the Windows Help application. This program lets you
specify the Help file you want to display to your user. The Declaration statement for the
WinHelp function is:
Declare Function WinHelp Lib "user32" Alias "WinHelpA" (ByVal hwnd As Long,
ByVal lpHelpFile As String, ByVal wCommand As Long, dwData As Any) As Long
The WinHelp function requires four arguments, as follows:
hWnd A long value containing the window's handle.
LpHelpFile A string containing the full path of the Help file to display.
Wcommand A long value that specifies the type of Help to display. This can be one of
the following values:
HELP_COMMAND Runs a Help macro or macro string. The
dwData argument is a string containing the
name of this macro.
*HELP_CONTENTS Displays the topic specified by the Contents
option in the [OPTIONS] section of the Help
file.
HELP_CONTEXT Displays the topic identified by the context
identifier defined in the [MAP] section of the
Help file. The dwData argument contains the
context identifier in a long unsigned integer.
*Note: New applications should use the HELP_FINDER value instead of this value.
This older command is provided for downward compatibility only.
In the list of options for the wCommand argument above, you can see that calling the
WinHelp function with the HELP_SETWINPOS value allows you to set the size and
position of your own Help window.
To show a Help window in a specific size, the dx and dy fields of the HELPWININFO
structure need to be defined. In the example program below, you set the values of these
two fields to 620 pixels each.
Likewise, you set the position of the Help window in the example program by setting the
X and Y fields of the HELPWININFO structure to 400 each.
Each time the program displays the Help window, the window appears at this new
position and in this new size.
Example Program
This program shows how to position the Windows Help file (or any other Help file) to a
specific location on the screen and in a specific size.
15. Add the following Constant, Type, and Declare statements to Module1.Bas
(note that the Declare statement must be typed as a single line of code):
16. Declare Function WinHelp Lib "user32" Alias "WinHelpA" (ByVal hwnd As Long,
17. ByVal lpHelpFile As String, ByVal wCommand As Long, dwData As Any) As Long
18. Type HELPWININFO
19. wStructSize As Long
20. x As Long
21. y As Long
22. dx As Long
23. dy As Long
24. wMax As Long
25. rgchMember As String * 2
26. End Type
27. Global Const HELP_SETWINPOS = &H203&
28. Global hwf As HELPWININFO
Run the example program by pressing F5. Form1 appears on the screen. Click the mouse
anywhere on the form to display the Help file for Windows. Notice that the window is
positioned in the lower-right corner of the screen and that the window's size has been set
to 620 x 620 pixels.
Abstract
This article explains how to position the mouse pointer over a specific control in a
Microsoft® Visual Basic® application.
To position the mouse pointer over a specific control, you need to use the Microsoft
Windows® application programming interface (API) GetWindowRect and
SetCursorPos functions. The GetWindowRect function is used to retrieve the
coordinates of a control. The Declare statement for the GetWindowRect function is:
Private Declare Function GetWindowRect Lib "user32" (ByVal hwnd As Long, lpRect
As RECT) As Long
The GetWindowRect function requires two arguments. The first argument is the handle
of the control. The second argument is the address of a RECT structure.
After calling the GetWindowRect function, the control's coordinates are stored in the
RECT structure. The RECT structure is defined as:
Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Note that the left, top, right, and bottom positions of the control are stored in the RECT
structure. After you know the exact position of the control, you need to use the
SetCursorPos function to position the mouse pointer directly over the control. The
Declare statement for the SetCursorPos function is:
Private Declare Function SetCursorPos Lib "user32" (ByVal x As Long,
ByVal y As Long) As Long
Then, to position the mouse pointer over the control, you retrieve the coordinates of the
control's upper-left corner by using the values stored in the Left field and Top field of the
RECT structure. Next, you call the SetCursorPos function with these two values to
actually position the mouse pointer over the control.
Example Program
This program shows how to move the mouse pointer over a specific control.
1. Create a new project in Visual Basic. Form1 is created by default.
16. From the Visual Basic Insert menu, select Module to create a new module.
Module1.Bas is created by default.
Abstract
This article explains how to determine the red, green, and blue components for a specific
color in your Microsoft® Visual Basic® application.
Example Program
This program shows how to separate the individual red, green, and blue components from
a given color.
3. Add the following code to the Click event for Command1 (note that the "MsgBox
=" statement must be typed as a single line of code):
4. Private Sub Command1_Click()
5. Dim C As Long
6. Dim Red As Integer
7. Dim Green As Integer
8. Dim Blue As Integer
9.
10. C = Command1.BackColor
11. Red = C Mod &H100
12. C = C \ &H100
13. Green = C Mod &H100
14. C = C \ &H100
15. Blue = C Mod &H100
16. MsgBox "Red = " & Str$(Red) & " Green: " & Str$(Green) & " Blue = "
17. & Str$(Blue)
18. End Sub
Run the example program by pressing F5. Click the Command Button control. A
message box appears indicating the individual red, green, and blue color values that
represent the button's BackColor property.
Abstract
This article explains how to extract the directory name and the filename from a path
when working with files and directories in your Microsoft® Visual Basic® application.
When you need to extract the filename element from a complete path, you need to search
for the last backslash character in the path string. To do this, you must first calculate the
length of the path. This can be done using the Visual Basic Len function. The Len
function returns the number of characters found in the specified string.
When you know the actual length of the path string, you can check each character,
beginning with the last character in the path string, to see whether it is a backslash
character. The Visual Basic Mid$ function can be used to perform this character
comparison. When you finally locate the backslash character, you know that this signals
the beginning of the filename stored within the path. You then use the Visual Basic
Right$ function to extract the filename from the longer string.
This same technique can be used to extract the directory name from the path. In this case,
however, the comparison routine starts from the beginning of the path string.
Example Program
This program shows how to extract both the directory name and the filename from a path.
Abstract
This article explains how to control the way in which a launched Microsoft® Visual
Basic® application is run.
The example program below launches the Windows 95 Notepad application. Note that
you specify the complete path to Notepad and launch the application as a normal process
(NORMAL_PRIORITY_CLASS).
After you call the CreateProcess function to launch the Notepad application, notice that
Notepad retains the focus. You cannot switch to another running application. This is
accomplished by executing the Windows API WaitForSingleObject function.
The WaitForSingleObject function forces the system to wait until a specific process has
finished its work. You pass the handle of the process you want to wait for and the length
of time, in milliseconds, to pause. In the example program below, the time-out value is
set to INFINITE, which means that the system will not resume running until the user has
quit Notepad.
The final step you must perform, after the user has quit Notepad, is to close the open
handle for the just-launched process. This removes all references to Notepad having been
launched.
Example Program
This program shows how to launch a Windows or MS-DOS® application from within
Microsoft Visual Basic. Control remains with the launched application until you quit that
application.
1. Create a new project in Visual Basic. Form1 is created by default.
22. Add the following code to Module1.Bas (note that each Declare statement must
be typed as a single line of code):
23. Type STARTUPINFO
24. cb As Long
25. lpReserved As String
26. lpDesktop As String
27. lpTitle As String
28. dwX As Long
29. dwY As Long
30. dwXSize As Long
31. dwYSize As Long
32. dwXCountChars As Long
33. dwYCountChars As Long
34. dwFillAttribute As Long
35. dwFlags As Long
36. wShowWindow As Integer
37. cbReserved2 As Integer
38. lpReserved2 As Long
39. hStdInput As Long
40. hStdOutput As Long
41. hStdError As Long
42. End Type
43. Type PROCESS_INFORMATION
44. hProcess As Long
45. hThread As Long
46. dwProcessID As Long
47. dwThreadID As Long
48. End Type
49. Global Const NORMAL_PRIORITY_CLASS = &H20&
50. Global Const INFINITE = -1&
Abstract
This article explains how to retrieve the current state of any virtual key in a Microsoft®
Visual Basic® application.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that the Declare statement must be typed as a single line
of code):
3. Private Declare Function GetKeyState Lib "user32" (ByVal nVirtKey As Long)
4. As Integer
5. Const VK_NUMLOCK = &H90
6. Const VK_SCROLL = &H91
7. Const VK_CAPITAL = &H14
8. Add a Command Button control to Form1. Command1 is created by default.
Abstract
This article explains how to determine the current screen resolution in a Microsoft®
Visual Basic® application.
Example Program
This program shows how to determine the current screen resolution in a Visual Basic
application.
1. Create a new project in Visual Basic. Form1 is created by default.
Abstract
When using the Microsoft® Windows® 95 operating system, you can delete a file from
disk by dragging the file or sending the file to the Recycle Bin. The file is not actually
removed from disk but is only marked for deletion by the system. When the Recycle Bin
is emptied, however, the file is physically removed from the disk. This article explains
how to send files to the Recycle Bin in a Microsoft Visual Basic® version 4.0
application.
Example Program
This program shows how to send files to the Recycle Bin in Windows 95.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following code to the General Declarations section of Form1 (note that
the Declare statement must be typed as a single line of code):
3. Public Const FO_DELETE = &H3
4. Public Const FOF_ALLOWUNDO = &H40
5. Declare Function SHFileOperation Lib "shell32.dll" Alias "SHFileOperationA"
6. (lpFileOp As SHFILEOPSTRUCT) As Long
7. Create a new function called ShellDelete. Add the following code to this
function:
8. Public Function ShellDelete(ParamArray vntFileName() As Variant)
9.
10. Dim I As Integer
11. Dim sFileNames As String
12. Dim SHFileOp As SHFILEOPSTRUCT
13.
14. For I = LBound(vntFileName) To UBound(vntFileName)
15. sFileNames = sFileNames & vntFileName(I) & vbNullChar
16. Next
17. sFileNames = sFileNames & vbNullChar
18.
19. With SHFileOp
20. .wFunc = FO_DELETE
21. .pFrom = sFileNames
22. .fFlags = FOF_ALLOWUNDO
23. End With
24.
25. ShellDelete = SHFileOperation(SHFileOp)
26.
27. End Function
28. Add a Command Button control to Form1. Command1 is created by default.
29. Add the following code to the Click event for Command1:
30. Private Sub Command1_Click()
31. Dim FileToKill As String
32.
33. FileToKill = "c:\test*.txt"
34. ShellDelete FileToKill
35. MsgBox "File(s) deleted"
36. End Sub
Abstract
In many Microsoft® Windows®-based applications, you can grab an item with a mouse,
"drag" the item to another location on the screen, and "drop" the item at that location.
This article explains how to add this drag-and-drop feature to your Microsoft Visual
Basic® applications.
You can add the drag-and-drop functionality to your Microsoft Visual Basic® application
by monitoring MouseUp and MouseDown events for a control. In the example program
below, you can drag an item from the first List Box control and drop that item on the
second List Box control.
When you initiate a drag-and-drop process, you select the item you want to drag by
pressing and holding down the left mouse button. You can then move (drag) the item to
Example Program
This program shows how to drag items from one List Box control and drop them on
another List Box control (note that each Private statement must be typed as a single line
of code):
18. Add the following code to the MouseDown event for List1:
19. Private Sub List1_MouseDown(Button As Integer, Shift As Integer,
20. X As Single, Y As Single)
21. DraggedItem = List1.List(List1.ListIndex)
22. List1.Enabled = False
32. Add the following code to the MouseDown event for List2:
33. Private Sub List2_MouseDown(Button As Integer, Shift As Integer,
34. X As Single, Y As Single)
35. DraggedItem = List2.List(List2.ListIndex)
36. List2.Enabled = False
37. End Sub
38. Add the following code to the MouseUp event for List2:
39. Private Sub List2_MouseUp(Button As Integer, Shift As Integer,
40. X As Single, Y As Single)
41. List1.Enabled = True
42. List1.RemoveItem List1.ListIndex
43. List2.AddItem DraggedItem
44. End Sub
Run the example program by pressing F5. Each List Box control contains five items.
Click on an item in the first List Box control, and drag this item to the second List Box
control. Release the mouse button to drop the item on the List Box control. The selected
item is removed from the first List Box control and is added to the second List Box
control. The situation can also be reversed—you can drag an item from the second List
Box control to the first List Box control.
Abstract
Within a Microsoft® Visual Basic® application, you can use the Microsoft Windows®
SystemParametersInfo to enable or disable fast task switching key combinations. This
article contains an example program that disables fast task switching.
Example Program
This program shows how to disable certain key combinations such as CTRL+ESC,
ALT+TAB, and CTRL+ALT+DEL. This, in effect, prevents the fast task switching
mechanism available under the Windows operating system.
Abstract
This article explains how you can use the Microsoft® Windows® GetComputerName
function to retrieve the computer name.
You can use the Windows application programming interface (API) GetComputerName
function in your Microsoft® Visual Basic® application to retrieve the name assigned to
your computer. To use this function, include the following Declare statement in your
project:
Private Declare Function GetComputerName Lib "kernel32" Alias
"GetComputerNameA" (ByVal sBuffer As String, lSize As Long)
As Long
The GetComputerName function requires two arguments. The first argument, sBuffer, is
the buffer that will hold the computer name after the function is executed. The size of the
buffer should be large enough to hold the entire name. The second argument, lSize, must
be initialized to the size of sBuffer.
After you have executed the GetComputerName function, the lSize variable will be set
to a count of the actual number of characters stored in the sBuffer string. This count value
does not include the terminating NULL character.
Example Program
This program shows how to retrieve the name assigned to a computer.
1. Create a new project in Visual Basic. Form1 is created by default.
15. Create a new function called NameOfPC. Add the following code to this
function:
16. Function NameOfPC(MachineName As String) As Long
17.
18. Dim NameSize As Long
19. Dim X As Long
20.
21. MachineName = Space$(16)
22. NameSize = Len(MachineName)
23. X = GetComputerName(MachineName, NameSize)
24. End Function
Run the example program by pressing F5. Click the Command Button control. The
name assigned to the computer appears in the Text Box control.
Abstract
This article explains how to design your Microsoft® Visual Basic® application so that
the user can search for an item in a Combo Box control.
Example Program
This program shows how to find an individual item in a Combo Box control.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that the Declare statement must be typed as a single line
of code):
3. Private Declare Function SendMessage Lib "user32" Alias "SendMessageA"
4. (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any)
5. As Long
6. Const CB_FINDSTRING = &H14C
7. Add the following code to the Form_Load event for Form1:
8. Private Sub Form_Load()
9. For X = 1 To 10
10. Combo1.AddItem "Item" & X
11. Next
12. End Sub
13. Add a Combo Box control to Form1. Combo1 is created by default.
15. Add the following code to the Click event for Command1:
16. Private Sub Command1_Click()
17. X = SendMessage(Combo1.hwnd, CB_FINDSTRING, -1, ByVal "Item5")
18. MsgBox "Index number for this entry is: " & Str$(X)
19. End Sub
Abstract
This article explains how to design your Microsoft® Visual Basic® application so that
after the user closes one child form on the screen the remaining child forms are
automatically cascaded.
Example Program
This program shows how to arrange child forms in a cascading format whenever child
forms are loaded or unloaded.
1. Create a new project in Visual Basic. Form1 is created by default. Set its
MDIChild property to True. Size the form so that it is relatively small in size.
7. Add a menu to MDIForm1. From the Visual Basic Tools menu, select Menu
Editor. Type the Caption as "&New Form" and the Name as NewForm.
Abstract
This article explains how to selectively enable and disable specific Tab buttons in a
Microsoft® Windows® 95 application.
In your program, you check the global array index for a specific Tab button. If it is
"enabled," then the SelectedItem property can be used to activate the code associated
with that Tab button. On the other hand, if that button has been flagged as "disabled," you
force the currently selected Tab button to remain the default Tab button—not the Tab
button the user just clicked.
Example Program
This program shows how to selectively enable and disable a specific Tab button on a
TabStrip control.
1. Create a new project in Visual Basic. Form1 is created by default.
Abstract
You can present information to the user of your Microsoft® Visual Basic® application in
the form of a Grid control, which displays the information in cells. This article explains
how to change the color of the cells and the color of the text within the cells.
The Grid control, however, does not provide any properties or methods for changing the
color of text within individual cells or the color of the cell itself. As a workaround to this
shortcoming, you can use a Picture Box control to change the appearance of cells in a
Grid control.
In the example program below, you set the BackColor and ForeColor properties of the
Picture Box control to the desired colors. Next, you use the Print method to print the
original contents of a cell in the Grid control to the Picture Box control. The final step is
to transfer the newly created image to the Grid control's Picture property. This, in turn,
displays the cell's text in a specific color or changes the cell's color.
Example Program
This program shows how to set the color of a Grid control's cells and the text within
specific cells.
1. Create a new project in Visual Basic. Form1 is created by default.
2. From the Visual Basic Tools menu, select Custom Controls. Select the "Microsoft
Grid Control" from the list of controls to add the Grid control to your toolbox.
3. Add a Grid control to Form1. Grid1 is created by default. Set its Rows property
to 5 and its Columns property to 5.
21. Add the following code to the Click event for Command1:
22. Private Sub Command1_Click()
23. Dim I As Integer
24. Dim J As Integer
25.
26. For I = 1 To Grid1.Rows - 1
27. For J = 1 To Grid1.Cols - 1
28. Call SetGridCell(Grid1, I, J, QBColor(I - 1), QBColor(15))
29. Next J
30. Next I
31. End Sub
32. Add a second Command Button control to Form1. Command2 is created by
default.
33. Add the following code to the Click event for Command2:
34. Private Sub Command2_Click()
35. Dim I As Integer
36. Dim J As Integer
37.
38. For I = 1 To Grid1.Rows - 1
39. For J = 1 To Grid1.Cols - 1
40. Call SetGridCell(Grid1, I, J, QBColor(15), QBColor(J - 1))
41. Next J
42. Next I
43.
44. End Sub
45. Add a third Command Button control to Form1. Command3 is created by
default.
Abstract
This article explains how you can easily recreate the structure of a disk by storing a list of
drives, directories, and/or files in a List Box control.
To use the SendMessage function, you must include the following Declare statement in
your project:
Private Declare Function SendMessageAny Lib "user32" Alias "SendMessageA"
The wParam argument for the LB_DIR message lets you specify the type of files you
want the List Box control to contain. You can set the wParam argument to include
normal, read-only, hidden, system, and archive files. In addition, you can also set the
wParam argument so that it sends drive and directory files to the List Box control.
Example Program
This program shows how to create a list of files and/or directories in a List Box control.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that the Declare statement must be typed as a single line
of code):
3. Private Declare Function AppendMenu Lib "user32" Alias "AppendMenuA"
4. (ByVal hMenu As Long, ByVal wFlags As Long, ByVal wIDNewItem As Long,
5. ByVal lpNewItem As String) As Long
6. Const WM_USER = &H400
7. Const LB_DIR = &H18D
8. Const DIR_NORMALFILES = &H0
9. Const DIR_READONLY = &H8001
10. Const DIR_HIDDEN = &H8002
11. Const DIR_SYSTEM = &H8004
12. Const DIR_DIRECTORIES = &H8010
13. Const DIR_ARCHIVED = &H8020
14. Const DIR_DRIVES = &HC000
15. Add a Command Button control to Form1. Command1 is created by default.
16. Add the following code to the Click event for Command1:
17. Private Sub Command1_Click()
18. Call ListFiles("c:\*.*")
19. End Sub
20. Add a List Box control to Form1. List1 is created by default.
21. Create a new subroutine called ListFiles. Add the following code to this
subroutine:
22. Sub ListFiles(sFileSpec As String)
23. Dim I As Long
24. List1.Clear
25. I = SendMessageAny(List1.hWnd, LB_DIR, DIR_DRIVES, ByVal sFileSpec)
26. I = SendMessageAny(List1.hWnd, LB_DIR, DIR_DIRECTORIES, ByVal sFileSpec)
Abstract
This article explains how to determine the total number of text lines that a printer can
accommodate on a single sheet of paper.
The ScaleHeight property tells you the horizontal coordinates for a single printed page.
If you need to determine how many lines of text can be printed on the default printer, you
must first retrieve the TextHeight method's value for the printer. Next, you retrieve the
ScaleHeight property's value for the printer and divide this value by the height of the text
string. The result is the total number of lines per page that you can send to the printer.
Example Program
This program tells you how many lines of text can be printed on a single sheet of paper.
Abstract
The Microsoft® Visual Basic® version 4.0 Rich Text Box control allows the user to
enter and edit text. In addition, this control provides more advanced formatting features
than the conventional TextBox control. This article explains how to display selected text
in different fonts in the Rich Text Box control.
In the example program below, you fill a Rich Text Box control with a list of all screen
fonts installed in the computer system. This is accomplished by using the TextRTF
property to tell the Rich Text Box control to display the text in the selected font.
Note The TextRTF property requires the Microsoft Windows® 95 or Microsoft
Windows NT® 3.51 or later operating system.
Example Program
This program shows how to display text in different fonts in a Rich Text Box control.
2. Add a Rich Text Box control to Form1. Rich-Text Box1 is created by default.
Abstract
This article explains how to prevent the user of your Microsoft® Visual Basic®
application from unintentionally quitting the application.
For example, when the user chooses the Close command from the Control-menu box to
quit an application, the UnloadMode variable contains a value of zero.
Example Program
This program shows how to prevent a user from accidentally choosing the Close
command on the program's Control-menu box.
1. Create a new project in Visual Basic. Form1 is created by default.
To add a new command to the Control menu, you need to perform several steps. First,
you need to use the Microsoft Windows® application programming interface (API)
GetSystemMenu function to retrieve the handle of the Control menu. (Note that this tip
applies to Windows 95 only.) The following code is the Declare statement for this
function:
Private Declare Function GetSystemMenu Lib "user32"
(ByVal hWnd As Long, ByVal bRevert As Long) As Long
The GetSystemMenu function requires two arguments. The hWnd argument is the
handle of the window that owns the Control menu. In this case, this argument is the
handle of your application's window. The bRevert argument tells the GetSystemMenu
function which of two actions you want to perform.
If the bRevert argument is set to True, the GetSystemMenu function will reset the
Control menu back to its original state (the Windows 95 default). Other applications, as
well as your own, may have previously modified the Control menu.
If the bRevert argument is set to False, the GetSystemMenu function will return the
handle of the current Control menu. This may or may not be the original Control menu
(the Windows 95 default).
In the example program below, you want to add a new command to the Control menu.
Therefore, you run the GetSystemMenu function with the bRevert argument set to False.
Once you have the handle of the Control menu, you need to call the Windows API
AppendMenu function. The following code is the Declare statement for this function:
Private Declare Function AppendMenu Lib "user32" Alias "AppendMenuA"
(ByVal hMenu As Long, ByVal wFlags As Long, ByVal wIDNewItem
As Long, ByVal lpNewItem As String) As Long
You can use the AppendMenu function to modify an existing menu's structure. You can
also use this function to modify the appearance of a new menu command. In this case,
however, you just want the command to appear as normal (that is, a textual description).
In the example program below, you use the AppendMenu function to add a new
command called "NewMenu" to the Control menu. However, in order to perform some
action when a user clicks NewMenu, you need to determine when the application
receives a Click event for that new menu command.
Example Program
This program shows how to add a new command to your application's Control menu.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following code to the General Declarations section of Form1 (note that
each Declare statement must be typed as a single line of code):
3. Private Declare Function AppendMenu Lib "user32" Alias "AppendMenuA"
4. (ByVal hMenu As Long, ByVal wFlags As Long, ByVal wIDNewItem As Long,
5. ByVal lpNewItem As String) As Long
6. Private Declare Function GetSystemMenu Lib "user32" (ByVal hWnd As Long, ByVal
7. bRevert As Long) As Long
8. Const WM_SYSCOMMAND = &H112
9. Const MF_STRING = &H0
10. Const SC_NEWMENU = 1
11. Add the following code to the Form_Load event for Form1:
12. Private Sub Form_Load()
13. Dim hw As Long
14. Dim hMenu As Long
15.
16. hw = Me.hWnd
17. hMenu = GetSystemMenu(hw, False)
18.
19. If AppendMenu(hMenu, MF_STRING, SC_NEWMENU, "&NewMenu") Then
20. MsgBlaster1.hWndTarget = hw
21. MsgBlaster1.AddMessage WM_SYSCOMMAND, POSTPROCESS
22. End If
23.
24. End Sub
25. Add a Message Blaster control to Form1. MsgBlaster1 is created by default.
Abstract
When displaying text in a Microsoft® Visual Basic® application, you may want to
specify which fonts are assigned to the text on the screen and the text sent to the printer.
This article explains how you can retrieve a list of screen fonts and a list of printer fonts
currently installed on your computer system.
Example Program
This program shows how to retrieve a list of all printer and screen fonts installed in the
computer system.
13. Add the following code to the Click event for Command2:
14. Private Sub Command2_Click()
15. List1.Clear
16. Dim X As Integer
17. For X = 0 To Screen.FontCount - 1
18. List1.AddItem Screen.Fonts(X)
19. Next X
20. End Sub
Run the example program by pressing F5. Click the first Command Button control. A
list of all printer fonts appears in the List Box control. Click the second Command
Button control. A list of all screen fonts appears in the List Box control.
Abstract
This article explains how to add a hot key that allows the user of a running application to
quickly switch to your Microsoft® Visual Basic® application.
The SendMessage function can be used to send a specific message to a window. To use
this function, add the following Declare statement to the General Declarations section of
your form:
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA"
(ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long,
lParam As Long) As Long
The SendMessage function takes the following four arguments:
hWnd A long value containing the window's handle. The message is sent to this
window.
wMsg A long value containing the message you want to send to hWnd.
wParam A long value containing additional message-dependent information.
lParam A long value containing additional message-dependent information.
In the example program below, you want to set PAUSE as the hot key to your
application. Because you want the application to be activated when PAUSE is pressed,
you need to send a WM_SETHOTKEY message to the application's window—in this
case, Form1. A WM_SETHOTKEY message is used to assign a specific key as an
application's hot key. Therefore, we need to use the SendMessage function to send a
WM_HOTKEY message to the application. This message is placed at the top of the
thread's message queue, which in turn allows the PAUSE key to gain immediate attention
when it is detected.
Note that a window can have only one hot key associated with it at any one time. In
addition, child windows cannot have hot keys associated with them. Finally, if you assign
a hot key to a window that already has a hot key assigned to it, the new hot key replaces
the original one.
Example Program
This program below shows how to add hot key access to your Visual Basic applications.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that the Declare statement must be typed as a single line
of code):
3. Private Declare Function SendMessage Lib "user32" Alias "SendMessageA"
4. (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long,
5. lParam As Long) As Long
Abstract
This article explains how to run MS-DOS®-based and Microsoft Windows®-based
applications from within a Microsoft Visual Basic® application.
Example Program
This program shows how to run an MS-DOS-based or Windows-based application in the
background. The application continues running in the background until the user
terminates it.
1. Create a new project in Visual Basic. Form1 is created by default.
13. Add the following code to the Click event for Command1:
14. Private Sub Command1_Click()
15. Dim JobToDo As String
16. JobToDo = "c:\windows\notepad.exe"
17. Shell32Bit JobToDo
18. End Sub
19. Create a new subroutine called Shell32Bit. Add the following code to this
subroutine:
20. Sub Shell32Bit(ByVal JobToDo As String)
21. Dim hProcess As Long
22. Dim RetVal As Long
23. 'The next line launches JobToDo as icon,
24. 'captures process ID
25. hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, Flase, Shell(JobToDo, 6))
26. Do
27. 'Get the status of the process
28. GetExitCodeProcess hProcess, RetVal
29. 'Sleep command recommended as well
30. 'as DoEvents
31. DoEvents: Sleep 100
32. 'Loop while the process is active
33. Loop While RetVal = STILL_ACTIVE
34. MsgBox "Notepad terminated by user"
35. End Sub
Run the example program by pressing F5. Click the Command Button control. The
example program runs the Windows Notepad application. Notice that the Notepad icon
appears in the Windows taskbar.
Notepad runs in the background until you quit it. The example program displays a
message box that indicates that Notepad was terminated
In a Microsoft Visual Basic® application, however, you can use the Windows application
programming interface (API) SystemParametersInfo function to select a new wallpaper.
This function can be used to retrieve or set many different Control Panel settings. The
following code is the Declare statement for this function:
Private Declare Function SystemParametersInfo Lib "user32" Alias
"SystemParametersInfoA" (ByVal uAction As Long, ByVal uParam
As Long, ByVal lpvParam As String, ByVal fuWinIni As Long) As Long
Note that the SystemParametersInfo function requires four arguments. The first
argument, uAction, is the setting that you want to retrieve or set. In this case, you want to
change the desktop wallpaper, so you use the SPI_SETDESKWALLPAPER constant
The second argument, uParam, is set to zero, because the wallpaper setting does not use
this argument. For the third argument, lpvParam, you must tell the
SystemParametersInfo function the filename for the wallpaper you want to use. You
must be sure to specify the file's full path in this argument. The fourth argument,
fuWinIni, can be one of two values that tells Windows 95 how to preserve the new
settings.
If the SPIF_UPDATEINIFILE constant is specified for the fuWinIni argument, Windows
95 saves the new settings to its user profile. If the constant
SPIF_SENDWININICHANGE is specified, however, the change is broadcast to
Windows 95 after the user profile is updated.
In the example program below, you can change the wallpaper setting to None or to the
PINSTRIPE bitmap image. When you change the current wallpaper setting to None, the
desktop is presented as a black background. In all other cases, the desktop wallpaper
displays the image stored in the specified bitmap file.
Example Program
This program below shows how to change the wallpaper in Windows 95.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following code to the General Declarations section of Form1 (note that
the Declare statement must be typed as a single line of code):
10. Add the following code to the Click event for Command1:
11. Private Sub Command1_Click()
12. Dim X As Long
13. X = SystemParametersInfo(SPI_SETDESKWALLPAPER, 0&, "(None)",
SPIF_UPDATEINIFILE Or SPIF_SENDWININICHANGE)
14. MsgBox "Wallpaper was removed"
15. End Sub
16. Add a second Command Button control to Form1. Command2 is created by
default. Set its Caption property to "Change Wallpaper".
17. Add the following code to the Click event for Command2:
18. Private Sub Command2_Click()
19. Dim FileName As String
20. Dim X As Long
21.
22. FileName = "c:\windows\pinstripe.bmp"
23.
24. X = SystemParametersInfo(SPI_SETDESKWALLPAPER, 0&, FileName,
SPIF_UPDATEINIFILE Or SPIF_SENDWININICHANGE)
25. MsgBox "Wallpaper was changed"
26. End Sub
Run the example program by pressing F5. Click the Remove Wallpaper command button.
The wallpaper is removed—Windows 95 displays a black background with no graphics.
Click the Change Wallpaper command button. The wallpaper is changed to the
PINSTRIPE bitmap image
Abstract
This article explains how to launch an applet in Microsoft® Windows® 95 Control Panel
from within a Microsoft Visual Basic® application.
Each time you want to launch a Control Panel applet, your Visual Basic statement must
include the syntax used above. In other words, you need only to substitute the name of
the .CPL file for "main.cpl" used above and specify the number of the particular applet
you want to execute. Also, if that applet requires additional command-line parameters,
you would specify these as the last parameter to the statement.
Each applet contained in a .CPL file is numbered starting from zero. If you don't specify
which applet you want to execute with the @value parameter, the first applet (@0) is the
one that is launched.
The following list provides a starting point for showing how to launch the different
applets found in Control Panel.
To launch Control Panel itself:
rundll32.exe shell32.dll,Control_RunDLL
To launch the Accessibility Options applet:
• General
• rundll32.exe shell32.dll,Control_RunDLL access.cpl,,5
• Display
• rundll32.exe shell32.dll,Control_RunDLL access.cpl,,3
• Keyboard
• rundll32.exe shell32.dll,Control_RunDLL access.cpl,,1
• Mouse
• rundll32.exe shell32.dll,Control_RunDLL access.cpl,,4
• Sound
Example Program
This program shows how to launch the Printers applet in Control Panel from within a
Visual Basic application.
1. Create a new project in Visual Basic. Form1 is created by default.
3. Add the following code to the Click event for Command1 (note that the Shell
statement must be typed exactly as shown):
4. Private Sub Command1_Click()
5. X = Shell("Rundll32.exe shell32.dll,Control_RunDLL main.cpl @2")
6. End Sub
Run the example program by pressing F5. Click the command button. The Printers applet
in Control Panel is launched.
Abstract
Each toolbar control in your Microsoft® Visual Basic® application can have a ToolTip,
which is a small pop-up window containing the name of the control. A ToolTip appears
whenever the mouse pointer is placed over a toolbar control. This article explains how to
To create a toolbar, you put a Toolbar control and an ImageList control on a form. Next,
the ImageList control is populated with icons or other graphic images. These images are
then assigned to the Buttons property of the Toolbar control.
You can assign ToolTip descriptions to each button on the toolbar by setting the toolbar's
ShowTips property to True and adding the text for the ToolTip description to the
ToolTip text box. When the mouse pointer is moved over a button on the toolbar, the
button's corresponding ToolTip text appears.
As an added feature, you can add a Status Bar control to the bottom of your form. A
Status Bar control contains information that is displayed to the user when certain events
occur in your application.
In the example program below, additional information is provided to the user when a
specific button is selected on the toolbar. This information appears in the Status Bar
control.
In order to provide this information in the Status Bar control, a method is needed for
determining which button the mouse pointer is over. You can calculate which button the
mouse pointer is over by monitoring the toolbar's MouseMove event.
The MouseMove event is triggered when the mouse is moved over the Toolbar control.
This event indicates the current position of the mouse on the Toolbar control in its X and
Y variables. If the current position of the mouse pointer corresponds to the position of a
toolbar button, a description can be displayed for that button in the Status Bar control.
Example Program
This program shows how to pass a description to a Status Bar control when an item is
selected on a Toolbar control.
1. Create a new project in Visual Basic. Form1 is created by default.
Abstract
In a Microsoft® Visual Basic® version 4.0 application, you may need to modify the date
and time stamp of a file. This article explains how this can be accomplished.
You must retrieve a handle to the file whose date and time stamp you want to modify.
This can be done by calling the Windows MAPI CreateFile function. When you have the
file's handle, a call to the SetFileTimeWrite function actually updates the date and time
stamp of the file.
Example Program
This program shows how to modify the date and time stamp of a file.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following code to the General Declarations section of Form1 (note that
each Declare statement must be typed as a single line of code):
3. Private Type FILETIME
4. dwLowDateTime As Long
5. dwHighDateTime As Long
6. End Type
7.
8. Private Type SYSTEMTIME
9. wYear As Integer
10. wMonth As Integer
11. wDayOfWeek As Integer
12. wDay As Integer
13. wHour As Integer
14. wMinute As Integer
15. wSecond As Integer
16. wMilliseconds As Integer
17. End Type
18.
19. Private Const GENERIC_WRITE = &H40000000
20. Private Const OPEN_EXISTING = 3
21. Private Const FILE_SHARE_READ = &H1
22. Private Const FILE_SHARE_WRITE = &H2
23.
24. Private Declare Function SetFileTimeWrite Lib "kernel32" Alias
25. "SetFileTime" (ByVal hFile As Long, ByVal MullP As Long,
26. ByVal NullP2 As Long, lpLastWriteTime As FILETIME) As Long
27. Private Declare Function SystemTimeToFileTime Lib "kernel32"
28. (lpSystemTime As SYSTEMTIME, lpFileTime As FILETIME) As Long
39. Add the following code to the Click event for Command1:
40. Private Sub Command1_Click()
41. Dim Year As Integer, Month As Integer
42. Dim Day As Integer, Hour As Integer
43. Dim Minute As Integer, Second As Integer
44. Dim TimeStamp As Variant
45. Dim Filename As String
46. Dim X As Integer
47.
48. Year = 1996
49. Month = 1
50. Day = 1
51. Hour = 1
52. Minute = 0
53. Second = 0
54.
55. TimeStamp = DateSerial(Year, Month, Day) + TimeSerial(Hour, Minute, Second)
56. Filename = "c:\autoexec.bat"
57.
58. X = ModifyFileStamp(Filename, TimeStamp)
59. MsgBox "The time and date stamp was updated"
60. End Sub
61. Create a new function called ModifyFileStamp. Add the following code to this
function:
62. Function ModifyFileStamp(Filename As String, TimeStamp As Variant)
63. As Integer
64. Dim X As Long
65. Dim Handle As Long
66. Dim System_Time As SYSTEMTIME
67. Dim File_Time As FILETIME
68. Dim Local_Time As FILETIME
69.
70. System_Time.wYear = Year(TimeStamp)
71. System_Time.wMonth = Month(TimeStamp)
72. System_Time.wDay = Day(TimeStamp)
73. System_Time.wDayOfWeek = WeekDay(TimeStamp) - 1
74. System_Time.wHour = Hour(TimeStamp)
75. System_Time.wSecond = Second(TimeStamp)
76. System_Time.wMilliseconds = 0
77.
78. 'convert the system time to a file time
79. X = SystemTimeToFileTime(System_Time, Local_Time)
Abstract
The Common Dialog control in Microsoft® Visual Basic® allows you to invoke Help
immediately and does not require that you use a dialog box. This article explains how to
use the Common Dialog control to access specific Microsoft Windows® Help files.
Finally, you set the HelpCommand property of the Common Dialog control to
HELP_KEY. This allows us to perform a context-sensitive search in the Help file.
Example Program
This program shows how to access a Windows Help file based on a specific string in a
Text Box control.
1. Create a new project in Visual Basic. Form1 is created by default.
Abstract
This article explains how to prevent the context menu from appearing when the user of
your Microsoft® Visual Basic® application uses the right mouse button to click a Text
Box control.
In the example program below, you want to ignore all right-clicks for the Text Box
control. To accomplish this, you supply Message Blaster with the handle of the Text
Box control and the message you want to trap.
If a right-click is detected while the program is running, the Message Blaster custom
control fools the operating system into believing that no such action was received.
Message Blaster is used to send an EATMESSAGE message to the operating system.
This, in effect, prevents the context menu from appearing.
Example Program
This program shows how to prevent the context menu from appearing when you right-
click on a Text Box control.
1. Create a new project in Visual Basic. Form1 is created by default.
Abstract
This article explains how, from within a Microsoft® Visual Basic® version 4.0
application, you can retrieve information about a specific file stored on disk. This
information may include the date and time when the file was initially created, when the
file was last accessed, and any number of other details.
Example Program
This program shows how to retrieve information about a specific file.
2. From the Visual Basic Insert menu, select Module to create a new module.
Module1.Bas is created by default.
3. Add the following code to Module1.Bas (note that each Declare statement must
be typed as a single line of code):
4. Declare Function OpenFile Lib "kernel32" (ByVal lpFileName As String,
5. lpReOpenBuff As OFSTRUCT, ByVal wStyle As Long) As Long
6. Declare Function GetFileInformationByHandle Lib "kernel32" (ByVal hFile
7. As Long, lpFileInformation As BY_HANDLE_FILE_INFORMATION) As Long
8. Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
9. Declare Function FileTimeToSystemTime Lib "kernel32" (lpFileTime As FileTime,
10. lpSystemTime As SYSTEMTIME) As Long
11. Public Const OFS_MAXPATHNAME = 128
12. Public Const OF_READ = &H0
13. Type OFSTRUCT
14. cBytes As Byte
15. fFixedDisk As Byte
16. nErrCode As Integer
17. Reserved1 As Integer
18. Reserved2 As Integer
19. szPathName(OFS_MAXPATHNAME) As Byte
20. End Type
21. Type SYSTEMTIME
22. wYear As Integer
23. wMonth As Integer
48. Add the following code to the Click event for Command1:
49. Private Sub Command1_Click()
50. Dim Ret As Long
51. Dim FileHandle As Long
52. Dim FileInfo As BY_HANDLE_FILE_INFORMATION
53. Dim lpReOpenBuff As OFSTRUCT
54. Dim FileTime As SYSTEMTIME
55.
56. FileHandle = OpenFile("c:\autoexec.bat", lpReOpenBuff, OF_READ)
57. Ret = GetFileInformationByHandle(FileHandle, FileInfo)
58.
59. Ret = FileTimeToSystemTime(FileInfo.ftCreationTime, FileTime)
60. Print "File created on " & FileTime.wYear, FileTime.wMonth,
61. FileTime.wDay
62.
63. Ret = FileTimeToSystemTime(FileInfo.ftLastAccessTime, FileTime)
64. Print "File last accessed on: " & FileTime.wYear, FileTime.wMonth,
65. FileTime.wDay
66.
67. Ret = FileTimeToSystemTime(FileInfo.ftLastWriteTime, FileTime)
68. Print "File last written to: " & FileTime.wYear, FileTime.wMonth,
69. FileTime.wDay
70.
71. Print "Volume Serial Number is: " & FileInfo.dwVolumeSerialNumber
72. Print "File attributes are: " & FileInfo.dwFileAttributes
73.
74.
75. Ret = CloseHandle(FileHandle)
76. End Sub
Abstract
This article explains how to save and later retrieve the contents of the Microsoft® Visual
Basic® version 4.0 List Box control to and from a file on disk.
You can save the contents of a List Box control to a sequential file on disk by first saving
each entry in the control to an array. To do this, you would run the following code
fragment:
For i = 0 To List1.ListCount - 1
A(i) = List1.List(i)
Next I
The total number of items stored in the List Box control is retrieved from the ListCount
property. Next, the array A(i) is created, where the i variable holds a count of the current
item being processed. As each item is retrieved from the List Box control, it is saved in
the array.
At this point, you use the Visual Basic Write # statement to save each item in the array to
a disk file. Similarly, when you reload the items from the disk file to the List Box
control, you use the Input # statement.
Example Program
This program shows how to save the contents of a List Box control to a file on disk. In
addition, you are shown how to retrieve the same items from the data file to the List Box
control.
1. Create a new project in Visual Basic. Form1 is created by default.
13. Add the following code to the Click event for Command1:
14. Private Sub Command1_Click()
15. For i = 0 To List1.ListCount - 1
16. A(i) = List1.List(i)
17. Next i
18. ItemCount = List1.ListCount
19. Open "c:\temp.txt" For Output As #1
20. For i = 0 To ItemCount - 1
21. Write #1, A(i)
22. Next i
23. Close #1
24. MsgBox "Data has been saved"
25.
26. End Sub
27. Add a second Command Button control to Form1. Command2 is created by
default.
28. Add the following code to the Click event for Command2:
29. Private Sub Command2_Click()
30. List1.Clear
31. Open "c:\temp.txt" For Input As #1
32. Do Until EOF(1)
33. Input #1, b$
34. List1.AddItem b$
35. Loop
36. Close #1
37.
38. End Sub
Run the example program by pressing F5. The program displays twenty items in the List
Box control. Click the first Command Button control. The contents of the List Box
control are saved to a file on disk. Click the second Command Button control. The
contents of the file on disk are retrieved into the List Box control.
Abstract
This article explains how to retrieve the amount of available disk space from within a
Microsoft® Visual Basic® application.
After executing the GetDiskFreeSpace function, either a value of True is returned if the
function was successful or a value of False if the function was not successful.
To calculate the total number of bytes available on the disk, you need to multiply the
number of bytes per sector by the number of sectors per cluster. Then, multiply this result
by the number of free clusters on the disk. This total gives you the number of bytes of
free space on the disk.
2. Add a Text Box control to Form1. Text1 is created by default. Set its MultiLine
property to True.
48. Add the following Type, Constant, and Declare statements to Module1.Bas
(note that the Declare statement must be typed as a single line of code):
49. Declare Function GetDiskFreeSpace Lib "kernel32" Alias "GetDiskFreeSpaceA"
50. (ByVal lpRootPathName As String, lpSectorsPerCluster As Long,
51. lpBytesPerSector As Long, lpNumberOfFreeClusters As Long,
52. lpTotalNumberOfClusters As Long) As Long
53. Type DISKSPACEINFO
54. RootPath As String * 3
55. FreeBytes As Long
56. TotalBytes As Long
57. FreePcnt As Single
58. UsedPcnt As Single
59. End Type
60. Global CurrentDisk As DISKSPACEINFO
Run the example program by pressing F5. Click the Command Button control. The
program displays the number and percentage of free bytes of disk space, and the total
number and percentage of bytes used.
Abstract
This article explains how to create a list of all currently running tasks on the Microsoft®
Windows® 95 operating system.
After you have retrieved the application's window handle, you can use the Windows API
GetParent function to retrieve this window's child window handle. Next, you call the
Windows API GetWindowText and GetWindowTextLength functions to retrieve the
text in the window's title bar and the length of this text, respectively. You can then use
the text string in your own application. For example, you can save the title bar text to a
List Box control.
All of the above steps are repeated until you have processed all running tasks. You know
that you have gone through each task when the current window is that of your own
application.
Example Program
This program shows how to create a list of all currently running tasks in Windows 95.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that each Declare statement must be typed as a single line
of code):
3. Private Declare Function GetWindow Lib "user32"
4. (ByVal hwnd As Long, ByVal wCmd As Long) As Long
5. Private Declare Function GetParent Lib "user32" (ByVal hwnd As Long) As Long
6. Private Declare Function GetWindowTextLength Lib "user32" Alias "GetWindowTextLengthA"
(ByVal hwnd As Long) As Long
7. Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA"
8. (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
9. Const GW_HWNDFIRST = 0
10. Const GW_HWNDNEXT = 2
12. Add the following code to the Click event for Command1:
13. Private Sub Command1_Click()
14. LoadTaskList
15. End Sub
16. Add a List Box control to Form1. List1 is created by default.
17. Create a new subroutine called LoadTaskList. Add the following code to this
subroutine:
18. Sub LoadTaskList()
19. Dim CurrWnd As Long
20. Dim Length As Long
21. Dim TaskName As String
22. Dim Parent As Long
23.
24. List1.Clear
25. CurrWnd = GetWindow(Form1.hwnd, GW_HWNDFIRST)
26.
27. While CurrWnd <> 0
28. Parent = GetParent(CurrWnd)
29. Length = GetWindowTextLength(CurrWnd)
30. TaskName = Space$(Length + 1)
31. Length = GetWindowText(CurrWnd, TaskName, Length + 1)
32. TaskName = Left$(TaskName, Len(TaskName) - 1)
33. If Length > 0 Then
34. If TaskName <> Me.Caption Then
35. List1.AddItem TaskName
36. End If
37. End If
38. CurrWnd = GetWindow(CurrWnd, GW_HWNDNEXT)
39. DoEvents
40. Wend
41. End Sub
Run the example program by pressing F5. Click the Command Button control. A list of
all currently running tasks on the Windows 95 operating system appears in the List Box
control.
Abstract
This article explains how to force a Combo Box control to drop down its list box when
the ENTER key is pressed in a Microsoft® Visual Basic® application.
The Dropdown Combo style of the Combo Box control is displayed with the arrow and
text box portion of the control slightly separated. You must click the down arrow to select
items from the Combo Box control.
The Simple Combo style of the Combo Box control displays its list box immediately.
The disadvantage of this style is that it takes up more space in your window.
The Dropdown List style of the Combo Box control is almost identical to the
Dropdown Combo style. However, this style does not allow you to modify the Text
property of this control.
Note that most applications use a Combo Box control with its Style property set to
Dropdown Combo. Instead of clicking on the arrow to cause the Combo Box control to
display its list box, it is more convenient to press the ENTER key.
Each time a key is pressed, the Combo Box control's KeyPress event is triggered
(providing that the Combo Box control has the focus, of course). By monitoring this
event, you can determine whether a user pressed ENTER. You know the user pressed
ENTER if the KeyAscii value is 13.
After you have determined that ENTER was indeed pressed, you send a
CB_SHOWDROPDOWN message to the Combo Box control by using the Microsoft
Windows® application programming interface (API) SendMessage function. If this
message is sent to the control with a parameter of True, the Combo Box control drops
down its list box. If this message is sent to the Combo Box control with a parameter of
False, however, the list box would not be dropped down.
Example Program
This program shows how to force a Combo Box control to drop down when the ENTER
key is pressed.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that the Declare statement must be typed as a single line
of code):
3. Const WM_USER = &H400
4. Const CB_SHOWDROPDOWN = &H14F
5. Private Declare Function SendMessage Lib "user32" Alias "SendMessageA"
6. (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As
7. Long) As Long
15. Add the following code to the KeyPress event for Combo1:
16. Private Sub Combo1_KeyPress(KeyAscii As Integer)
17. Dim I As Long
18. If KeyAscii = 13 Then
19. I = SendMessage(Combo1.hwnd, CB_SHOWDROPDOWN, True, 0&)
20. End If
21. End Sub
Run the example program by pressing F5. While the Combo Box control has the focus,
press ENTER. The Combo Box control displays its list box.
Abstract
This article includes a Microsoft® Visual Basic® version 4.0 program that runs on the
Microsoft Windows® 95 operating system. You can use this program to search a disk
drive for a file or group of files. The search can be initiated from the root directory of the
disk drive or from any specific directory. The found files are listed in a List Box control
with their corresponding paths.
When you have retrieved the names of all directories stored under the target directory,
you call the List_Files procedure. The List_Files procedure then performs another
recursive search routine by using the same technique as the Get_Files procedure to find
all files that match the target filename. The full path of the found file is added to the
second List Box control. When all files and directories have been processed, the program
quits.
Example Program
This program shows how to search for a filename by specifying a directory from which to
begin the search.
1. Create a new project in Visual Basic. Form1 is created by default.
63. Add a Text Box control to Form1. Text1 is created by default. Set its Text
property to an empty string.
64. Add a second Label control to Form1. Label2 is created by default. Set its
Caption property to "Filename".
65. Add a second Text Box control to Form1. Text2 is created by default. Set its Text
property to an empty string.
66. Add a List Box control to Form1. List1 is created by default. Set its Visible
property to False.
67. Add a second List Box control to Form1. List2 is created by default.
69. Add the following code to the Click event for Command1:
70. Private Sub Command1_Click()
71. Dim XLen As Integer
72.
73. XLen = Len(Text1.Text)
74.
75. If Mid$(Text1.Text, XLen, 1) = "\" Then
76. StrtPath = Left$(Text1.Text, XLen - 1)
77. Else
78. StrtPath = Text1.Text
79. End If
80.
81. XFilename = Text2.Text
82.
83. List1.Clear
84. List2.Clear
85.
86. List1.AddItem StrtPath
87. Get_Files StrtPath
88. List_Files
89.
90. If List2.ListCount = 0 Then
91. MsgBox "Unable to find file"
92. Else
93. MsgBox "Search completed"
94. End If
95. End Sub
Run the example program by pressing F5. Suppose that you want to find all files with the
extension .TXT in the directory C:\DOCS. In the first Text Box control, type the name of
the directory from which you want to start the search. Next, type the name of the file you
want to find in this starting directory. You may use any valid MS-DOS filename, as well
as wildcard characters. Click the Search button. The program displays the results of its
search in the List Box control and displays a message box indicating that the search has
been completed.
Abstract
Because Microsoft Windows 95 users may have different screen resolution settings, you
may need to set the screen resolution to a specific setting while your Microsoft® Visual
Example Program
This program shows how to set the screen resolution from within a Visual Basic
application.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following code to the General Declarations section of Form1 (note that
each Declare statement must be typed as a single line of code):
3. Option Explicit
4. Private Declare Function EnumDisplaySettings Lib "user32" Alias
5. "EnumDisplaySettingsA" (ByVal lpszDeviceName As Long,
6. ByVal iModeNum As Long, lpDevMode As Any) As Boolean
7.
8. Private Declare Function ChangeDisplaySettings Lib "user32" Alias
9. "ChangeDisplaySettingsA" (lpDevMode As Any, ByVal dwflags As Long) As Long
10.
11. Const CCDEVICENAME = 32
12. Const CCFORMNAME = 32
13. Const DM_PELSWIDTH = &H80000
48. Add the following code to the Click event for Command1:
49. Private Sub Command1_Click()
50. Dim a As Boolean
51. Dim i&
52. i=0
53. Do
54. a = EnumDisplaySettings(0&, i&, DevM)
55. i=i+1
56. Loop Until (a = False)
57. End Sub
58. Add a second Command Button control to Form1. Command2 is created by
default.
59. Add the following code to the Click event for Command2:
60. Private Sub Command2_Click()
61. Dim b&
62. DevM.dmFields = DM_PELSWIDTH Or DM_PELSHEIGHT
Abstract
The Microsoft® Visual Basic® version 4.0 Setup program allows you to create a
standard installation program for your Visual Basic application. The Setup program, as
with other Microsoft Setup programs, draws a gradient background pattern, usually in a
blue color. This article explains how to draw gradient backgrounds in a Visual Basic
application.
To display a window with a gradient background, you simply paint thin rectangles in
different colors on the form. This gives the form a fade-to-black effect.
The RealizePalette function lets you select a logical palette for a device context, such as
a window. This allows you to use a larger number of colors in your application without
interfering with the colors used by other forms (windows) in your program. After calling
the RealizePalette function, you need only select the colors with which you want to paint
the rectangles and the gradient background effect is created.
Example Program
This program shows how to draw a gradient background on a form/window in Visual
Basic.
1. Create a new project in Visual Basic. Form1 is created by default.
18. Add the following code to the Click event for Command1:
19. Private Sub Command1_Click()
20. dummy = RealizePalette(Form1.hdc)
21. Form1.Scale (0, 0)-(256, 1)
22. For I = 0 To 255
23. Form1.Line (I, 0)-(I + 1, 1), RGB(RedColor(I + 1), _
24. GreenColor(I + 1), BlueColor(I + 1)), BF
25. Form1.ForeColor = RGB(RedColor(I + 1), GreenColor(I + 1), _
26. BlueColor(I + 1))
27. Next I
28. End Sub
29. Add a second Command Button control to Form1. Command2 is created by
default.
30. Add the following code to the Click event for Command2:
31. Private Sub Command2_Click()
32. dummy = RealizePalette(Form1.hdc)
33. Form1.Scale (0, 0)-(1, 256)
34. For I = 0 To 255
35. Form1.Line (0, I)-(1, I + 1), RGB(RedColor(I + 1), _
36. GreenColor(I + 1), BlueColor(I + 1)), BF
37. Form1.ForeColor = RGB(RedColor(I + 1), GreenColor(I + 1), _
38. BlueColor(I + 1))
39. Next I
40. End Sub
Run the example program by pressing When you click the first Command Button
control, the program draws the black-to-blue gradient background horizontally across the
form. Clicking the second Command Button control instructs the program to draw the
gradient background vertically down the form.
Abstract
The Microsoft® Windows® File Manager and Explorer applications use an Outline
control to display directories and files in a hierarchical list. This article explains how to
populate the Microsoft Visual Basic® version 4.0 Outline control using this same
technique.
Example Program
This program shows how to populate the Outline control with all directory and files
stored on a disk drive.
1. Create a new project in Visual Basic. Form1 is created by default.
Abstract
Under the Microsoft® Windows® 95 operating system, you can assign a long filename to
a file instead of being limited to an 8.3 format. This article explains how to retrieve the
short (MS-DOS®) filename assigned to a long filename from within a Microsoft Visual
Basic® version 4.0 application.
Example Program
This program shows how to retrieve the short (MS-DOS) filename assigned to a long
filename.
1. Create a new project in Visual Basic. Form1 is created by default.
22. Add a second Text Box control to Form1. Text2 is created by default.
Abstract
In Microsoft® Visual Basic® version 4.0, the Microsoft Windows® application
programming interface (API) ShellAbout function lets you display the standard
Microsoft Windows About dialog box seen in applications such as Notepad and Explorer.
This article explains how to use an icon other than the default Microsoft Windows icon
that appears in the About dialog box of your Visual Basic 4.0 application.
You can tell the ShellAbout function to display your About dialog box with an icon of
your choice rather than having the function use the Microsoft Windows icon. You can do
this by using the icon that is assigned to your Visual Basic 4.0 application, for example.
Then, when you call the ShellAbout function, you specify the handle of that icon
(Me.Icon) as the hIcon argument to the function.
Example Program
This program shows how to change the icon that appears in the About dialog box when
using the ShellAbout function to create the dialog box.
1. Create a new project in Visual Basic. Form1 is created by default. Set the Icon
property of Form1 to an icon of your choice.
Abstract
This article explains how to add visual appeal to your Microsoft® Visual Basic® version
4.0 application by changing the color of a Label control when the mouse is positioned
over that control.
Example Program
This program shows how to change the color of a Label control when the mouse pointer
is positioned over the control.
1. Create a new project in Visual Basic. Form1 is created by default.
22. Add the following code to the MouseMove event for Label1 (note that the
Private statement must be typed as a single line of code):
23. Private Sub Label1_MouseMove(Button As Integer, Shift As Integer, X As Single,
24. Y As Single)
25. Call ChangeColor(Label1)
26. End Sub
27. Add a second Label control to Form1. Label2 is created by default.
28. Add the following code to the MouseMove event for Label2 (note that the
Private statement must be typed as a single line of code):
29. Private Sub Label2_MouseMove(Button As Integer, Shift As Integer, X As Single,
30. Y As Single)
31. Call ChangeColor(Label2)
32. End Sub
33. Create a new subroutine called ChangeColor. Add the following code to this
subroutine:
34. Sub ChangeColor(Lbl As Label)
35. If Lbl.ForeColor <> MyFocusColor Then
36. Lbl.ForeColor = MyFocusColor
37. End If
38. End Sub
Run the example program by pressing F5. Each time you move the mouse pointer over
the Label control, the color of the Label control is changed
Abstract
This article explains how to determine whether a window or control has a scroll bar
associated with it when your Microsoft® Visual Basic® 4.0 application is running.
You can call the GetWindowLong function to determine whether a control has a scroll
bar. The GetWindowLong function requires two arguments: the handle of the window
you want to retrieve information for, and the type of information you want to retrieve. In
this case, you tell the GetWindowLong function to retrieve the style of the window
(GWL_STYLE).
After the GetWindowLong function is called, you use the Visual Basic AND operator to
find out whether the style of the window is set to that of a vertical scroll bar (&H200000).
If this statement indicates that a scroll bar is present, the expression returns a True value.
Example Program
This program shows how to determine whether a control has a scroll bar.
1. Create a new project in Visual Basic. Form1 is created by default.
2. Add the following code to the General Declarations section of Form1 (note that
the Declare statement must be typed as a single line of code):
3. Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA"
4. (ByVal hwnd As Long, ByVal nIndex As Long) As Long
5. Const GWL_STYLE = (-16)
6. Add a File List Box control to Form1. File1 is created by default.
Abstract
Using the Microsoft® Windows® application programming interface (API)
SystemParametersInfo function, you can remove or change the default desktop
wallpaper from within your Microsoft Visual Basic® 4.0 application.
Example Program
This program shows how to remove and select a new desktop wallpaper from within a
Visual Basic application.
2. Add the following Constant and Declare statements to the General Declarations
section of Form1 (note that the Declare statement must be typed as a single line
of code):
3. Private Declare Function SystemParametersInfo Lib "user32" Alias
4. "SystemParametersInfoA" (ByVal uAction As Long, ByVal uParam As Long,
5. ByVal lpvParam As String, ByVal fuWinIni As Long) As Long
6. Const SPIF_UPDATEINIFILE = &H1
7. Const SPI_SETDESKWALLPAPER = 20
8. Const SPIF_SENDWININICHANGE = &H2
9. Add a Command Button control to Form1. Command1 is created by default. Set
its Caption property to "Remove Wallpaper".
10. Add the following code to the Click event for Command1 (note that the "X ="
statement must be typed as a single line of code):
11. Private Sub Command1_Click()
12. Dim X As Long
13. X = SystemParametersInfo(SPI_SETDESKWALLPAPER, 0&, "(None)",
14. SPIF_UPDATEINIFILE Or SPIF_SENDWININICHANGE)
15. MsgBox "Wallpaper was removed"
16. End Sub
17. Add a second Command Button control to Form1. Command2 is created by
default. Set its Caption property to "Change Wallpaper".
18. Add the following code to the Click event for Command2 (note that the "X ="
statement must be typed as a single line of code):
19. Private Sub Command2_Click()
20. Dim FileName As String
21. Dim X As Long
22.
23. FileName = "c:\windows\pinstripe.bmp"
24.
25. X = SystemParametersInfo(SPI_SETDESKWALLPAPER, 0&, FileName,
26. SPIF_UPDATEINIFILE Or SPIF_SENDWININICHANGE)
27. MsgBox "Wallpaper was changed"
28. End Sub
Run the example program by pressing F5. To remove the wallpaper, click the "Remove
Wallpaper" command button. Windows 95 displays a black background with no graphics
whatsoever. Click the "Change Wallpaper" command button to change the wallpaper to
the PINSTRIPE.BMP image.