[ WAA
Home | ProjeX
Home | Download ProjeX | Using ProjeX | ProjeX
FAQ| About
WAA]
By Mike Witcombe (Witcombe@waa-inc.com)
Visual Basic has a ready built dialog to let the user easily browse and select a file from available folders. This functions well under many circumstances but gives the user little control, to get this control we can use Window’s GetOpenFileNameA API function.
In the General Declarations section we need to set up a type structure for the information we will be passing to the Windows function
Public Type OPENFILENAME
lStructsize As Long
hwndOwner As Long
hInstance As Long
lpstrFilter As String
lpstrCustomFilter As String
nMaxCustFilter As String
nFilterIndex As Long
lpstrFile As String
nMaxFile As Long
lpstrFileTitle As String
nMaxFileTitle As Long
lpstrInitialDir As String
lpstrTitle As String
flags As Long
nFileOffset As Integer
nFileExtension As Integer
lpstrDefExt As String
lCustData As Long
lpfnHook As Long
lpTemplateName As String
End Type
And also declare the function’s name we are going to be using and API code library the function belongs.
Declare Function
GetOpenFileName _
Lib "comdlg32.dll" Alias "GetOpenFileNameA"
_
(lpOpenFilename As
OPENFILENAME) _
As Long
Now let’s define a simple subroutine to demonstrate how to use our function ‘GetFileName’ to get a filename and return it to our Visual Basic program.
Sub FileSelectUtility()
Dim WindowTitle As String
Dim SelectedFile As String
WindowTitle = "Select
the file you want to analyse ..."
SelectedFile =
GetFileName(WindowTitle)
If SelectedFile =
"" Then End 'we did not
select a file
MsgBox "You have
selected " & SelectedFile
End Sub
The function itself takes the dialog title we want displayed, passes it to the Windows function and returns back with a filename if one is selected.
' GetFileName was produced by witcombe@waa-inc.com
Dim popen As OPENFILENAME
Dim x As Long
Const Max_Length = 256
With popen
.lStructsize = Len(popen)
.hwndOwner = HWnd
.lpstrFilter = "All files (*.*)" & Chr$(0) &
"*.*" & Chr$(0)
.nFilterIndex = 1
.lpstrFile = String(Max_Length, 0)
.nMaxFile = Max_Length - 1
.lpstrFileTitle = .lpstrFile
.nMaxFileTitle = Max_Length - 1
.lpstrInitialDir = 0&
.lpstrTitle = "Open"
End With
' Title in the dialog
If IsMissing(Title) Then
popen.lpstrTitle = "Select a file"
Else
popen.lpstrTitle = Title
End If
' Display the dialog
x = GetOpenFileName(popen)
If x Then
GetFileName = Left$(popen.lpstrFile, popen.nMaxFile)
Else
GetFileName = ""
End If
End Function
The Windows API contains many other useful functions, the above naming convention is based on a function GetDirectory which is available at www.jwalk.com/
Copyright Mike Witcombe of WAA, 1996-2001.
For problems or questions regarding this web contact [waa-inc@excite.com].
Last updated: January ,(, /),(.