How to Obtain the Startup Directory for a Visual Basic Program

ID Number: Q84484

1.00

WINDOWS

Summary:

In many cases, you may want to find a program's startup directory.

Visual Basic does not provide a direct way to determine this. However,

two functions contained in the Windows API will return the directory

where the code for a running program is stored.

This information applies to Microsoft Visual Basic programming system

version 1.0 for Windows.

More Information:

You might think that it would be fairly easy to determine where the

code for an executing Visual Basic application is located. However,

Visual Basic provides no way to reliably retrieve a program's startup

directory. The CurDir$ function returns the current directory, but a

program can be started from a directory other than it's own. Thus,

CurDir$ cannot be used to determine the startup directory.

The following steps demonstrate one way to determine where the code

for a running program is stored:

1. Run Visual Basic, or from the File menu, choose New Project (ALT,

F, N) if Visual Basic is already running. Form1 is created by

default.

2. Type the following Windows API function declarations into the

global module (GLOBAL.BAS):

Declare Function GetModuleHandle% Lib "kernel" (ByVal FileName$)

Declare Function GetModuleFileName% Lib "kernel" (ByVal hModule%,

ByVal FileName$, ByVal nSize%) 'This goes on line above!!

' Each function declaration must be typed on a single line.

3. Draw a command button on Form1. Double-click on it to bring up the

Click procedure. Enter the following code into the Click procedure:

Sub Command1_Click ()

hModule% = GetModuleHandle("MYPROG.EXE")

Buffer$ = Space$(255)

Length% = GetModuleFileName(hModule%, Buffer$, Len(Buffer$))

Buffer$ = Left$(Buffer$,Length%)

Msg$ = "Startup path and filename: " + Buffer$

MsgBox Msg$

End Sub

4. From the File menu, choose Make EXE File, and give it the name

MYPROG.EXE.

5. Run MYPROG.EXE. Click on the command button. A message box should

appear that displays your program's startup directory.

Additional reference words: 1.00