Visual Basic Common Dialog Routines
GetOpenFileName: File Open Common Dialog Basics
     
Posted:   Friday December 27, 1996
Updated:   Monday December 26, 2011
     
Applies to:   VB4-32, VB5, VB6
Developed with:   VB4-32, Windows 95
Revised with:   VB6, Windows NT4
OS restrictions:   None
Author:   VBnet - Randy Birch
     
Related:   GetOpenFileName: File Open/Save Common Dialog API - Overview
GetSaveFileName: File Save Common Dialog Basics
GetOpenFileName: File Dialog Centering using a Callback
GetOpenFileName: Advanced Dialog Centering using a Callback
GetOpenFileName: Customize File Open/Save Common Dialog Controls
     
 Prerequisites
None.

vbnsFileOpen.gif (6930 bytes)This page provides the detailed code and descriptions required for the Common Dialog GetOpenFileName API, as well as showing how to retrieve the constituent parts of the file string returned.

Code comments are at a minimum here. For detailed descriptions of the OPENFILENAME structure used and the dialog flags, see the overview listed above.

Special note on NULLS: these calls require that vbNullChar (or Chr$(0)) be used as null separators or null string terminators. These APIs will not work on NT if vbNullString is used.

For a discussion on modifying the OPENFILENAME structure in order to display the new Windows 2000 or Windows XP-style Open and Save dialogs, please see the comments section in the page GetOpenFileName: File Dialog Centering using a Callback (note: a hook is not required to display this new-style dialog - it just so happens that page is the one I chose to explain this on.)

 BAS Module Code
Place the following code into the general declarations area of a bas module:

Option Explicit
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Copyright 1996-2011 VBnet/Randy Birch, All Rights Reserved.
' Some pages may also contain other copyrights by the author.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Distribution: You can freely use this code in your own
'               applications, but you may not reproduce 
'               or publish this code on any web site,
'               online service, or distribute as source 
'               on any media without express permission.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Public Const OFN_ALLOWMULTISELECT As Long = &H200 
Public Const OFN_CREATEPROMPT As Long = &H2000 
Public Const OFN_ENABLEHOOK As Long = &H20 
Public Const OFN_ENABLETEMPLATE As Long = &H40 
Public Const OFN_ENABLETEMPLATEHANDLE As Long = &H80 
Public Const OFN_EXPLORER As Long = &H80000 
Public Const OFN_EXTENSIONDIFFERENT As Long = &H400 
Public Const OFN_FILEMUSTEXIST As Long = &H1000 
Public Const OFN_HIDEREADONLY As Long = &H4 
Public Const OFN_LONGNAMES As Long = &H200000 
Public Const OFN_NOCHANGEDIR As Long = &H8 
Public Const OFN_NODEREFERENCELINKS As Long = &H100000 
Public Const OFN_NOLONGNAMES As Long = &H40000 
Public Const OFN_NONETWORKBUTTON As Long = &H20000 
Public Const OFN_NOREADONLYRETURN As Long = &H8000& 'see comments 
Public Const OFN_NOTESTFILECREATE As Long = &H10000 
Public Const OFN_NOVALIDATE As Long = &H100 
Public Const OFN_OVERWRITEPROMPT As Long = &H2 
Public Const OFN_PATHMUSTEXIST As Long = &H800 
Public Const OFN_READONLY As Long = &H1 
Public Const OFN_SHAREAWARE As Long = &H4000 
Public Const OFN_SHAREFALLTHROUGH As Long = 2 
Public Const OFN_SHAREWARN As Long = 0 
Public Const OFN_SHARENOWARN As Long = 1 
Public Const OFN_SHOWHELP As Long = &H10 
Public Const OFS_MAXPATHNAME As Long = 260 

'OFS_FILE_OPEN_FLAGS and OFS_FILE_SAVE_FLAGS below 
'are mine to save long statements; they're not 
'a standard Win32 type. 
Public Const OFS_FILE_OPEN_FLAGS = OFN_EXPLORER _
             Or OFN_LONGNAMES _
             Or OFN_CREATEPROMPT _
             Or OFN_NODEREFERENCELINKS 

Public Const OFS_FILE_SAVE_FLAGS = OFN_EXPLORER _
             Or OFN_LONGNAMES _
             Or OFN_OVERWRITEPROMPT _
             Or OFN_HIDEREADONLY 

Public Type OPENFILENAME
  nStructSize       As Long
  hWndOwner         As Long
  hInstance         As Long
  sFilter           As String
  sCustomFilter     As String
  nMaxCustFilter    As Long
  nFilterIndex      As Long
  sFile             As String
  nMaxFile          As Long
  sFileTitle        As String
  nMaxTitle         As Long
  sInitialDir       As String
  sDialogTitle      As String
  flags             As Long
  nFileOffset       As Integer
  nFileExtension    As Integer
  sDefFileExt       As String
  nCustData         As Long
  fnHook            As Long
  sTemplateName     As String
End Type

Public OFN As OPENFILENAME 

Public Declare Function GetOpenFileName Lib "comdlg32" _
    Alias "GetOpenFileNameA" _ 
   (pOpenfilename As OPENFILENAME) As Long 

Public Declare Function GetSaveFileName Lib "comdlg32" _
   Alias "GetSaveFileNameA" _
  (pOpenfilename As OPENFILENAME) As Long

Public Declare Function GetShortPathName Lib "kernel32" _ 
    Alias "GetShortPathNameA" _ 
   (ByVal lpszLongPath As String, _
    ByVal lpszShortPath As String, _
    ByVal cchBuffer As Long) As Long 
 Form Code
To a new project form add a command button (Command1), seven Text boxes (Text1-Text7), a List (List1) and a Checkbox (Check1).  The text boxes are oriented beginning with the first label/textbox as Text/Label #1, the next #2 and so on. Add the following code to the form:

Option Explicit

Private Sub Command1_Click()

  'used in call setup
   Dim sFilters As String
   
  'used after call
   Dim pos As Long
   Dim buff As String
   Dim sLongname As String
   Dim sShortname As String

  'create a string of filters for the dialog
   sFilters = "Visual Basic Forms" & vbNullChar & "*.frm" & vbNullChar & _
              "Visual Basic Modules" & vbNullChar & "*.bas" & vbNullChar & _
              "Visual Basic Projects" & vbNullChar & "*.vbp" & vbNullChar & _
              "Text Files" & vbNullChar & "*.txt" & vbNullChar & _
              "All Files" & vbNullChar & "*.*" & vbNullChar & vbNullChar
 
 
   With OFN
   
      'size of the OFN structure
      .nStructSize = Len(OFN)
      
      'window owning the dialog
      .hWndOwner = Form1.hWnd
      
      'filters (patterns) for the dropdown combo
      .sFilter = sFilters
      
      'index to the initial filter
      .nFilterIndex = 2
      
      'default filename, plus additional padding
      'for the user's final selection(s). Must be
      'double-null terminated
      .sFile = "Untitled.bas" & Space$(1024) & vbNullChar & vbNullChar
      
      'the size of the buffer
      .nMaxFile = Len(.sFile)
      
      'default extension applied to
      'file if it has no extention
      .sDefFileExt = "bas" & vbNullChar & vbNullChar
                                     
      'space for the file title if a single selection
      'made, double-null terminated, and its size
      .sFileTitle = vbNullChar & Space$(512) & vbNullChar & vbNullChar
      .nMaxTitle = Len(OFN.sFileTitle)
      
      'starting folder, double-null terminated
      .sInitialDir = "d:\vb5" & vbNullChar & vbNullChar
      
      'the dialog title
      .sDialogTitle = "VBnet GetOpenFileName Demo"
      
      'default open flags and multiselect
      .flags = OFS_FILE_OPEN_FLAGS Or _
               OFN_ALLOWMULTISELECT 
   End With
   
   
  'call the API
   If GetOpenFileName(OFN) Then
    
     'remove trailing pair of terminating nulls
     'and trim returned file string
      buff = Trim$(Left$(OFN.sFile, Len(OFN.sFile) - 2))
    
     'show the members of the returned sFile
     'string in the listbox. If multiselect,
     'the first member is the path, and the
     'remaining members are the files under
     'that path selected.
      Do While Len(buff) > 3
      
         List1.AddItem StripDelimitedItem(buff, vbNullChar)
      
      Loop
   
     'see illustration for descriptions
      Text1.Text = OFN.sFile
      Text2.Text = Left$(OFN.sFile, OFN.nFileOffset)
      Text3.Text = Mid$(OFN.sFile, OFN.nFileOffset + 1, _
                   Len(OFN.sFile) - OFN.nFileOffset - 1)
      
     'note the extention and filetitle are not
     'returned in when in multiselect mode
      Text4.Text = Mid$(OFN.sFile, OFN.nFileExtension + 1, _
                        Len(OFN.sFile) - OFN.nFileExtension)
      Text5.Text = OFN.sFileTitle
      
      sLongname = OFN.sFileTitle
      sShortname = Space$(128)
      pos = GetShortPathName(sLongname, sShortname, Len(sShortname))
      Text6.Text = LCase$(Left$(sShortname, pos))
     
      sLongname = OFN.sFile
      sShortname = Space$(128)
      pos = GetShortPathName(sLongname, sShortname, Len(sShortname))
      Text7.Text = LCase$(Left$(sShortname, pos))
  
      Check1.Value = Abs((OFN.flags And OFN_READONLY))
  
  End If

End Sub


Private Function StripDelimitedItem(startStrg As String, _
                                    delimiter As String) As String

  'take a string separated by nulls,
  'split off 1 item, and shorten the string
  'so the next item is ready for removal.
   Dim pos As Long
   Dim item As String
   
   pos = InStr(1, startStrg, delimiter)
   
   If pos Then

      StripDelimitedItem = Mid$(startStrg, 1, pos)
      startStrg = Mid$(startStrg, pos + 1, Len(startStrg))
    
   End If

End Function


Private Function TrimNull(item As String) As String

   Dim pos As Integer
   
   pos = InStr(item, Chr$(0))
   If pos Then
      TrimNull = Left$(item, pos - 1)
   Else
      TrimNull = item
   End If
  
End Function
 Comments
Once the displayed dialog has closed, the file details for the selected or new file(s) will be returned on the form.

For a discussion on modifying the OPENFILENAME structure in order to display the new Windows 2000 or Windows XP-style Open and Save dialogs, please see the comments section in the page GetOpenFileName: File Dialog Centering using a Callback (note: a hook is not required to display this new-style dialog - it just so happens that page is the one I chose to explain this on.)

Note: re OFN_NOREADONLYRETURN: This value is define in the header files as &H8000, which unfortunately is -32768 in VB.  The correct value required 32768, so an ampersand (&) must be appended to this value to force VB to cast this to a Long.   This is even true if the constant is defined As Long in the declare.  If you use this constant in your apps and the file dialog either does not appear or the app crashes without an error, check this value.


 
 

PayPal Link
Make payments with PayPal - it's fast, free and secure!

 
 
 
 

Copyright 1996-2011 VBnet and Randy Birch. All Rights Reserved.
Terms of Use  |  Your Privacy

 

Hit Counter