How to do things in Visual Basic

Question – I need to know how to open a COM port with VB 4.0 32-bit so I can check if the modem is online or not.

Answer – Use the communications control’s (mscomm32.ocx) port open property.

Example:
MyPort.PortOpen = True to open port, and MyPort.PortOpen = False to close
port.

Submitted by Demir Ateser, Intermec Corp.

Question – What is the easiest way to play a small wav file in VB app as background music?

Answer – The easiest way is to use the freeware WAVEMIX.DLL from Microsoft, which allows you
to play up to 8 wave sounds simultaneously, and includes settings for playing a wave repeatedly in the
background.

Question – Is there an API call i can perform to find out how much HD space left?

Answer – This code is for HD partitions under 2 gigs.

Declare Function GetDiskFreeSpace Lib “kernel32” _
Alias “GetDiskFreeSpaceA” _
(ByVal lpRootPathName As String, _
lpSectorsPerCluster As Long, _
lpBytesPerSector As Long, _
lpNumberOfFreeClusters As Long, _
lpTtoalNumberOfClusters As Long) As Long

Dim r As Long
Dim DrvSectors As Long
Dim DrvBytesPerSector As Long
Dim DrvFreeClusters As Long
Dim DrvTotalClusters As Long

Dim DrvSpaceTotal As Long
Dim DrvSpaceFree As Long
Dim DrvSpaceUsed As Long

Dim RootPathName As String

‘the drive to find

RootPathName$ = “c:”

‘get the drive’s disk parameters
r = GetDiskFreeSpace(RootPathName, DrvSectors, DrvBytesPerSector,
DrvFreeClusters, DrvTotalClusters)

DrvSpaceTotal = (DrvSectors * DrvBytesPerSector * DrvTotalClusters)
DrvSpaceFree = (DrvSectors * DrvBytesPerSector * DrvFreeClusters)
DrvSpaceUsed = DrvSpaceTotal – DrvSpaceFree

Submitted by Randy Birch, MVP Visual Basic.

You can also get the free disk space on a hard disk from an API called GetDiskFreeSpace.

Please try the following example…
Open a project.
Open a module

Add the following. declaration in the module

Declare Function GetDiskFreeSpace Lib “kernel32” Alias “GetDiskFreeSpaceA”
(ByVal lpRootPathName As String, lpSectorsPerCluster As Long,
lpBytesPerSector As Long, lpNumberOfFreeClusters As Long,
lpTtoalNumberOfClusters As Long) As Long

In the form,

Add a command button,
Add two labels and add two edit boxes besides them

In the click event of the command button, place the folowing code.

Private Sub Command1_Click()
Dim x, lpSectorsPerCluster, lpBytesPerSector, lpNumberOfFreeClusters,
lpTtoalNumberOfClusters As Long

lpSectorsPerCluster = 0
lpBytesPerSector = 0
lpNumberOfFreeClusters = 0
lpTtoalNumberOfClusters = 0
lpRootname$ = “c:”
x = GetDiskFreeSpace(lpRootname$, lpSectorsPerCluster, lpBytesPerSector,
lpNumberOfFreeClusters, lpTtoalNumberOfClusters)
Text1.Text = lpTtoalNumberOfClusters * lpSectorsPerCluster *
lpBytesPerSector / 1000000
Text2.Text = lpNumberOfFreeClusters * lpSectorsPerCluster *
lpBytesPerSector / 1000000

End Sub

Run the project.

The first edit box will tell you the Total space on your drive and the second one will tell you the free
space on the drive all in Megs. This worked for me in VB 5.0 prof edition.

Submitted by D.K.Seshadri, Aditi Corp.

Question – Creating Screen Savers – How is it done?

Answer – Overview:

Have you ever wanted to write your own screensaver, but was told, “You can’t do that in Visual Basic!”
In fact, one person I heard from told me that Microsoft said that screensavers were impossible in
Visual Basic. I didn’t believe hem, and this is the result.

Windows screensavers are easy and fun to write in Visual Basic, but there are some very important
things to know.

Experts can go straight to the Code Section of this document.

Description: & Application Title:

A Windows screensaver is nothing more that a regular Windows executable file that has been
renamed with the .scr extension. In Visual Basic, when you are making the executable file, you
will need to set the Application Title in the Make EXE dialog box. This Application Title MUST
be set to “SCRNSAVE title”, where title is the text you want displayed in the Control Panel
screensaver dropdown box.

Command Line Arguments:

When Windows starts up a screensaver it calls it with the “/s” argument, and when it wants to
Setup the screensaver it uses the “/c” argument. So, we use a code module called SCRNSAV.BAS.
In SCRNSAV.BAS you will see that a Select Case statement is used to capture this argument.
You will need to change the Startup Form in the options|Project Dialog Box to Sub Main.

Telling Windows that the Saver is Running:

How long Windows waits before loading the screensaver is specified in the Control Panel.
But if your screensaver doesn’t tell Windows that it is running, Windows will reload the
screensaver after that time passes again, even though the screensaver is already running.
At first I thought I could remedy this situation by using VB 3.0’s App object. The App.PrevInstance
property will tell you whether or not there is a previous instance loaded.

This should’ve worked, and I got many comments saying that I must have messed something up,
but it didn’t. For some reason, with the screensaver this kills both instances, not just the second.
But there is a way out. To fix this I found a Windows API call which tells Windows that the
screensaver is inactive, so don’t load one. To use this API you need to use the API call
SystemParametersInfo. This function is used to change system wide parameters, such
as whether or not the screensaver is active. Be careful when using this call, since changes are
permanent. You will need to make sure that your screensaver turns the screensaver back off
when it has ended.

See Sub Main, and Sub ExitNice in the Code Section.

Hiding The Cursor:

When you write a screensaver, you’ll want it to hide the mouse cursor as well as whatever else
your saver does. To do this you need to use the API call – ShowCursor. When ShowCursor( False )
is called, the cursor is hidden; when ShowCursor( True ) is called, the cursor is re-displayed.
The Windows cursor is a shared object, so if your process hides it your process needs to redisplay
it as well. See Code section.

Knowing when to end:

When your screensaver ends is up to you, but generally you’ll want it to end if any of the following occur:
mouse moves, button pressed, key pressed. To do this you will need to call a routine to exit properly from
each of these events in your screensaver form. See SaverForm. You need to call this routine because this
is where the other half of the SystemParametersInfo call is made. If this is left out, the screensaver won’t
run again after it wakes up. Another problem is that the MouseMove message is sent if the cursor is over
the form, REGARDLESS if it is moved or not. So, you need to check to see if it has moved somehow.
Code:
ScrnSave.Bas

declarations
DefInt A-Z
Const SWP_NOSIZE = 1
Const SWP_NOMOVE = 2
Const SPI_SETSCREENSAVEACTIVE = 17
Declare Function ShowCursor Lib “User” (ByVal bShow As Integer) As
Integer
Declare Sub SetWindowPos Lib “User” (ByVal hWnd, ByVal After,
ByVal X, ByVal Y,
ByVal cx, ByVal cy, ByVal Flags)
Declare Function SystemParametersInfo Lib “User” (ByVal uAction As
Integer, ByVal
uparam As Integer, lpvParam As Any, ByVal fuWinIni
As Integer) As Integer

Sub Main
Select Case Command$
Case “/s”, “/S”
Res = SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, 0, ByVal
0&, 0)
Load SaverForm
SetWindowPos SaverForm.hWnd, -1, 0, 0, 0, 0, SWP_NOMOVE Or
SWP_NOSIZE
ok = DoEvents()
Case “/c”, “/C”
ConfigForm.Show
End Select
End Sub

You may also need to add some initialization code for whatever your
screensaver does.

Sub ExitNice
Res = ShowCursor(True) ‘Turn the cursor back on
‘reset screensaver
Res = SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, 1, ByVal 0&,
0)
End
End Sub

Saver.Frm
Form_Load
WindowState = 2 ‘Maximize the screensaver
Me.Show ‘Show the form
This = ShowCursor(False) ‘Hide the cursor

Form_MouseMove
If (OldX = 0) And (OldY = 0) Then
OldX = X
OldY = Y
Exit Sub
End If

If (OldX X) Or (OldY Y) Then
ExitNice
Else
OldX = 0
OldX = 0
End If

Form_Click

ExitNice

Form_MouseDown
ExitNice

Form_KeyDown
ExitNice

Form_KeyPress
ExitNice

Config.Frm

Windows will pass the “/c” argument to Sub Main if the “Setup” option is chosen from control panel.
Here you can setup specific options for your screensaver. You might want to save these options in a .ini file
(win.ini or your own). Its up to you! If your Config.Frm has a “Test” feature which starts the screensaver
from the Config form, then you will need to be careful about remembering to turn on the cursor after the
screensaver starts, and then turn it off before it ends.
Submitted By: Peter Provost in an aticle to Visual Basic tips & Tricks

Question – How do I write code to sort?

Answer – They teach you the “Bubble” sort at school and that’s it. So years later that super program you have written still relies on Noddy’s Toy Town code to do the sorting. Here is VB code to run 6 types of sort. It is from a program called SortDemo that ships with QBASIC and I have converted it to VB.

This is what you do:

Create a form. Put on it: one picture box (name PB), 3 command
buttons, and 1 Frame containing 6 Opiton buttons as a control array.

The captions for the options are:

0 = Insertion
1 = Bubble
2 = Heap
3 = Exchange
4 = Shell
5 = Quick

I’ll leave it to you to figure out the Command buttons & their code.

Note: you must make the Picture Box Width greater than the height.
Oblong I think its called.

Add a module. Cut&Paste the first bit of the code (TYPE declarations)
into it.

Cut&Paste the rest of the code into the form.

Light blue touch paper (F5) and stand back.

If I had a web page I would post this program there, but I haven’t so
I won’t.

Jeff.

P.s. Drinks vouchers gratefully accepted.

This must be in a .BAS module
========================================================

‘ Define the data type used to hold the information for each colored
bar:
Type SortType
Length As Integer ‘ Bar length (the element compared
‘ in the different sorts)
ColorVal As Integer ‘ Bar color

End Type

========================================================
Paste into .FRM general decalrations

‘ Declare global variables, and allocate storage space for them.
SortArray
‘ and SortBackup are both arrays of the data type SortType defined
above:
Dim SortArray() As SortType, SortBackup() As SortType
Dim Selection, MaxRow, InitRow, MaxColors

Dim OptionChoice

Sub bDone_Click ()
End
End Sub

Sub bOK_Click ()
Reinitialize
End Sub

Sub bRun_Click ()
‘ Branch to the appropriate procedure depending on the key
typed:
Select Case OptionChoice
Case 0
InsertionSort
Case 1
BubbleSort
Case 2
HeapSort
Case 3
ExchangeSort
Case 4
ShellSort
Case 5
QuickSort 1, MaxRow
End Select

End Sub

Static Sub BubbleSort ()
‘ ============================== BubbleSort
==================================
‘ The BubbleSort algorithm cycles through SortArray, comparing
adjacent
‘ elements and swapping pairs that are out of order. It continues
to
‘ do this until no pairs are swapped.

============================================================================

Limit = MaxRow
Do
Switcharoo = 0
For Row = 1 To (Limit – 1)

‘ Two adjacent elements are out of order, so swap their
values
‘ and redraw those two bars:
If SortArray(Row).Length > SortArray(Row + 1).Length Then
Swap SortArray(Row), SortArray(Row + 1)
SwapBars Row, Row + 1
Switcharoo = Row
End If
Next Row

‘ Sort on next pass only to where the last Switcharoo was made:
Limit = Switcharoo
Loop While Switcharoo

End Sub

Static Sub ElapsedTime (CurrentRow)
For ZZZ = 1 To 32767: Next
‘ some code will never be obsolete
End Sub

Static Sub ExchangeSort ()
‘ ============================= ExchangeSort
=================================
‘ The ExchangeSort compares each element in SortArray – starting
with
‘ the first element – with every following element. If any of the
‘ following elements is smaller than the current element, it is
exchanged
‘ with the current element and the process is repeated for the next
‘ element in SortArray.

============================================================================

For Row = 1 To MaxRow
SmallestRow = Row
For J = Row + 1 To MaxRow
If SortArray(J).Length Row Then
Swap SortArray(Row), SortArray(SmallestRow)
SwapBars Row, SmallestRow
End If
Next Row
End Sub

Sub Form_Activate ()
Initialize
End Sub

Sub Form_Load ()
PB.ScaleMode = 6
MaxRow = Int(PB.ScaleHeight – 2)
ReDim SortArray(1 To MaxRow), SortBackup(1 To MaxRow)

End Sub

Static Sub HeapSort ()
‘ =============================== HeapSort
===================================
‘ The HeapSort procedure works by calling two other procedures –
PercolateUp
‘ and PercolateDown. PercolateUp turns SortArray into a “heap,”
which has
‘ the properties outlined in the diagram below:

‘ SortArray(1)
‘ /
‘ SortArray(2) SortArray(3)
‘ / /
‘ SortArray(4) SortArray(5) SortArray(6) SortArray(7)
‘ / / / /
‘ … … … … … … … …


‘ where each “parent node” is greater than each of its “child nodes”;
for
‘ example, SortArray(1) is greater than SortArray(2) or SortArray(3),
‘ SortArray(3) is greater than SortArray(6) or SortArray(7), and so
forth.

‘ Therefore, once the first FOR…NEXT loop in HeapSort is finished,
the
‘ largest element is in SortArray(1).

‘ The second FOR…NEXT loop in HeapSort swaps the element in
SortArray(1)
‘ with the element in MaxRow, rebuilds the heap (with PercolateDown)
for
‘ MaxRow – 1, then swaps the element in SortArray(1) with the element
in
‘ MaxRow – 1, rebuilds the heap for MaxRow – 2, and continues in this
way
‘ until the array is sorted.

============================================================================

For I = 2 To MaxRow
PercolateUp I
Next I

For I = MaxRow To 2 Step -1
Swap SortArray(1), SortArray(I)
SwapBars 1, I
PercolateDown I – 1
Next I
End Sub

Static Sub Initialize ()
‘ ============================== Initialize
==================================

‘ Initializes the SortBackup and OptionTitle arrays. It also calls
the
‘ CheckScreen, BoxInit, and RandInt% procedures.

============================================================================

ReDim TempArray(1 To MaxRow)

For I = 1 To MaxRow
TempArray(I) = I
Next I

MaxIndex = MaxRow

Randomize Timer ‘ Seed the random-number generator.
For I = 1 To MaxRow

‘ Call RandInt% to find a random element in TempArray between 1
‘ and MaxIndex, then assign the value in that element to
BarLength:
Index = RandInt%(1, MaxIndex)
BarLength = TempArray(Index)

‘ Overwrite the value in TempArray(Index) with the value in
‘ TempArray(MaxIndex) so the value in TempArray(Index) is
‘ chosen only once:
TempArray(Index) = TempArray(MaxIndex)

‘ Decrease the value of MaxIndex so that TempArray(MaxIndex)
can’t
‘ be chosen on the next pass through the loop:
MaxIndex = MaxIndex – 1

‘ Assign the BarLength value to the .Length element, then store
SortBackup(I).Length = BarLength

‘ Store the appropriate color value in the .ColorVal element:
SortBackup(I).ColorVal = (BarLength Mod 15) + 1
Next I

PB.Cls
Reinitialize ‘ Assign values in SortBackup to SortArray and
draw
‘ unsorted bars on the screen.
Pause = 2 ‘ Initialize Pause to 2 clock ticks (@ 1/9
second).

End Sub

Static Sub InsertionSort ()
‘ ============================= InsertionSort
================================
‘ The InsertionSort procedure compares the length of each successive
‘ element in SortArray with the lengths of all the preceding
elements.
‘ When the procedure finds the appropriate place for the new
element, it
‘ inserts the element in its new place, and moves all the other
elements
‘ down one place.

============================================================================

Dim TempVal As SortType
For Row = 2 To MaxRow
TempVal = SortArray(Row)
TempLength = TempVal.Length
For J = Row To 2 Step -1

‘ As long as the length of the J-1st element is greater than
the
‘ length of the original element in SortArray(Row), keep
shifting
‘ the array elements down:
If SortArray(J – 1).Length > TempLength Then
SortArray(J) = SortArray(J – 1)
PrintOneBar J ‘ Print the new bar.
ElapsedTime J ‘ Print the elapsed time.

‘ Otherwise, exit the FOR…NEXT loop:
Else
Exit For
End If
Next J

‘ Insert the original value of SortArray(Row) in SortArray(J):
SortArray(J) = TempVal
PrintOneBar J
ElapsedTime J
Next Row
End Sub

Sub Option1_Click (Index As Integer)
OptionChoice = Index
End Sub

Static Sub PercolateDown (MaxLevel)
‘ ============================ PercolateDown
=================================
‘ The PercolateDown procedure restores the elements of SortArray
from 1 to

‘ MaxLevel to a “heap” (see the diagram with the HeapSort
procedure).

============================================================================

I = 1

‘ Move the value in SortArray(1) down the heap until it has
‘ reached its proper node (that is, until it is less than its
parent
‘ node or until it has reached MaxLevel, the bottom of the current
heap):
Do
Child = 2 * I ‘ Get the subscript for the child
node.

‘ Reached the bottom of the heap, so exit this procedure:
If Child > MaxLevel Then Exit Do

‘ If there are two child nodes, find out which one is bigger:
If Child + 1 SortArray(Child).Length Then
Child = Child + 1
End If
End If

‘ Move the value down if it is still not bigger than either one
of
‘ its children:
If SortArray(I).Length SortArray(Parent).Length Then
Swap SortArray(Parent), SortArray(I)
SwapBars Parent, I
I = Parent

‘ Otherwise, the element has reached its proper place in the
heap,
‘ so exit this procedure:
Else
Exit Do
End If
Loop
End Sub

Static Sub PrintOneBar (Row)

‘ ============================== PrintOneBar
=================================
‘ Prints a line at the row indicated by the Row
‘ parameter, using the color in SortArray(Row).ColorVal.

============================================================================
PB.Line (1, Row)-(PB.ScaleWidth – 2, Row + 1), PB.BackColor, BF
PB.Line (1, Row)-(SortArray(Row).Length, Row + 1),
QBColor(SortArray(Row).ColorVal), BF
End Sub

Sub QuickSort (Low, High)
‘ ============================== QuickSort
===================================
‘ QuickSort works by picking a random “pivot” element in SortArray,
then
‘ moving every element that is bigger to one side of the pivot, and
every
‘ element that is smaller to the other side. QuickSort is then
called
‘ recursively with the two subdivisions created by the pivot. Once
the
‘ number of elements in a subdivision reaches two, the recursive
calls end
‘ and the array is sorted.

============================================================================

If Low SortArray(High).Length Then
Swap SortArray(Low), SortArray(High)
SwapBars Low, High
End If
Else

‘ Pick a pivot element at random, then move it to the end:
RandIndex = RandInt%(Low, High)
Swap SortArray(High), SortArray(RandIndex)
SwapBars High, RandIndex
Partit = SortArray(High).Length
Do

‘ Move in from both sides towards the pivot element:
I = Low: J = High
Do While (I < J) And (SortArray(I).Length I) And (SortArray(J).Length >= Partit)
J = J – 1
Loop

‘ If we haven’t reached the pivot element, it means that
two
‘ elements on either side are out of order, so swap them:
If I < J Then
Swap SortArray(I), SortArray(J)
SwapBars I, J
End If
Loop While I < J

' Move the pivot element back to its proper place in the
array:
Swap SortArray(I), SortArray(High)
SwapBars I, High

' Recursively call the QuickSort procedure (pass the smaller
' subdivision first to use less stack space):
If (I – Low) 0 ‘ Loop until offset gets to zero.
Limit = MaxRow – Offset
Do
Switcharoo = False ‘ Assume no Switcharooes at this
offset.

‘ Compare elements and Switcharoo ones out of order:
For Row = 1 To Limit
If SortArray(Row).Length > SortArray(Row + Offset).Length
Then
Swap SortArray(Row), SortArray(Row + Offset)
SwapBars Row, Row + Offset
Switcharoo = Row
End If
Next Row

‘ Sort on next pass only to where last Switcharoo was made:
Limit = Switcharoo – Offset
Loop While Switcharoo

‘ No Switcharooes at last offset, try one half as big:
Offset = Offset 2
Loop
End Sub

Sub Swap (Var1 As SortType, Var2 As SortType)
Dim temp As SortType
temp = Var1
Var1 = Var2
Var2 = temp
End Sub

Static Sub SwapBars (Row1, Row2)
‘ =============================== SwapBars
===================================
‘ Calls PrintOneBar twice to Switcharoo the two bars in Row1 and
Row2,
‘ then calls the ElapsedTime procedure.

============================================================================

PrintOneBar Row1
PrintOneBar Row2
ElapsedTime Row1
End Sub

Posted on usenet, August 1997

Question – How do I Format a disk in VB4?

Answer – Tip 10: Formatting a Disk – Created: March 1, 1995

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:

Error Code Description

0 – Out of memory
2 – File not found
3 – Path not found
5 – Sharing/protection error
6 – Each task requires separate data segments
10 – Windows version is incorrect
11 – Not valid .EXE file
12 – Cannot execute OS/2 application
13 – Cannot execute DOS 4.0 application
14 – EXE type is unknown
15 – Protected memory mode not supported by Windows
16 – Cannot load another instance of .EXE file
17 – Cannot load second instance in large-frame EMS mode
18 – Cannot load protected-mode application in real mode

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.. 1. The current directory
2.. 2. The Windows directory
3.. 3. The Windows System directory
4.. 4. The directory that contains the current task’s application file
5.. 5. All directories in the PATH environment variable
6.. 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.

We can tell Windows to execute the FORMAT command in Visual Basic with the
following statement:

x = WinExec(“dosprmpt.pif /c c:dosformat b: < c:response.tmp",
SW_HIDE)Each time MS-DOS formats a diskette, it asks you to press the enter
key to initiate the procedure. After the disk has been formatted, the
program asks you to type a Volume Label name and/or press the enter key.
Next, you are asked if you wish to format another diskette, to which you
respond with a "y" or "n" key.

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.. 1. Start a new project in Visual Basic. Form1 is created by default.
2.. 2. In the General Declarations section of Form1, add the following
three statements:

a.. Const Resp_File = "c:response.tmp"
b.. Const SW_HIDE = &H0
c.. Dim ActiveApps As Integer
1.. 3. In addition, add the following two Declare statements (note that
each statement should be typed as a single line of text):

a.. Declare Function WinExec Lib "Kernel" (ByVal lpCmdLine As String, ByVal
nCmdShow
b.. As Integer) As Integer
c.. Declare Function GetNumTasks Lib "Kernel" () As Integer
1.. 4. Add a command button control to Form1. Command1 is created by
default. Set its Caption property to "Format Disk".
2.. 5. Add the following code to the Click event of Command1:

a.. Sub Command1_Click()
b.. Cmd = Chr(13) & Chr(10) & Chr(13) & Chr(10) & "N" & Chr(13) &
Chr(10)
c.. FileNum = FreeFile
d.. Open Resp_File For Output As #FileNum
e.. Print #FileNum, Cmd
f.. Close #FileNum
g.. ActiveApps = GetNumTasks()
h.. X = WinExec("dosprmpt.pif /c c:dosformat b: ActiveApps
j.. X = DoEvents()
k.. Loop
l.. Kill Resp_File
m.. End Sub
Execute this demonstration program by pressing the f5 function key or by
selecting Run from the Visual Basic menu. Insert a floppy diskette into
drive B and click the “Format Disk” command button. Visual Basic will format
the diskette in drive B and return control to the demonstration program.

Question – Preventing Multiple Occurances of a VB App

Answer – There are at least three ways to prevent the same app from appearing more than once.

The knowledge base documents a reasonable one in article:
How to Prevent Multiple Instances of a VB Application

Article ID: Q102480

This relies on you having a constant caption title in your main window. If you change the
caption in your main window, check out VB Tips and Tricks newsletter. It is free, and full
of useful info. It contains two other ways to prevent your app from starting twice, which
rely a little less on the caption title.

Question – How do I play a WAV File in VB?

Answer – You do not need a custom control to play WAV files in VB.

See the following Knowledge Base article:

How to Play a Waveform (.WAV) Sound File in Visual Basic
Article ID: Q86281

Question – How to Invoke a Screen Saver with a Windows Message.

Answer – Here is how to invoke a screen saver directly.

‘Declare the SendMessage function. (Remember keep it on one line!)
Declare Function SendMessage Lib “User” (ByVal hWnd, ByVal wMsg,

ByVal wParam, lParam As Any) As Long

‘Declare the constants we’ll need
Global Const WM_SYSCOMMAND = &H112
Global Const SC_SCREENSAVE = &HF140

‘Put this wherever you need to invoke the screen saver

Dim result As Long
result = SendMessage(Form1.hWnd, WM_SYSCOMMAND, SC_SCREENSAVE, 0&)

Set Text Box to Read Only

Wayne Hendler posted the following note on setting text boxes to be read-only.
This allows you to prevent your users from editing the controls without worrying
about the background colors or setting global windows defaults.

This code will work with both text boxes and masked edit boxes.

In a BAS module enter the following declare (all on one line):

Declare Function SendMessageBynum& Lib “User” Alias “SendMessage” _
(ByVal hWnd%, ByVal wMsg%, ByVal wParam%, ByVal lParam&)

In your form load event, add the following for each text box you wish to disable:

Dim Message_Return As Integer

Const EM_SETREADONLY = &H400 + 31

Message_Return = SendMessageBynum(Text_Box.hWnd, EM_SETREADONLY,1, 0&)

By the way, if you change the third parm to 0 and reissue the statement, it will re-enable the text box.

Question – How to find out the free memory

Answer – Here is how to find it!.

From PSS ID Number: Q76247

In Windows version 3.1, a Windows application can obtain the amount of free system resources in two ways:
1. By calling the GetFreeSystemResources() function, which is exported by KERNEL
2. By calling the SystemHeapInfo() function, which is exported by the TOOLHELP.DLL dynamic-link library

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.