Visual Basic 6 function "SaveFile"

Go back

Below you'll find the source for the Visual Basic 6 function SaveFile.

Attribute VB_Name = "modSaveFile"
' This function is downloaded from:
' http://www.stefanthoolen.nl/archive/vb6-functions/
' 
' You may freely distribute this file but please leave all comments, including this one, in it.
' 
' @Author Stefan Thoolen <mail@stefanthoolen.nl>

Private Declare Function GetSaveFileNameA Lib "comdlg32.dll" (pOpenfilename As OPENFILENAME) As Long

Private Declare Function CommDlgExtendedError Lib "comdlg32.dll" () As Long

Private Const OFN_HIDEREADONLY = &H4

' See also: http://msdn.microsoft.com/en-us/library/ms646839(VS.85).aspx
Private Type OPENFILENAME
        lStructSize As Long
        hwndOwner As Long
        hInstance As Long
        lpstrFilter As String
        lpstrCustomFilter As String
        nMaxCustFilter As Long
        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

''
' Displays an Save File dialog box
' @param    Long    hwnd        The Window Handler of it's caller
' @param    String  filter      A file filter (ex.: "Textfiles|*.txt|All files (*.*)|*.*")
' @param    String  title       The title of the dialog
' @param    String  path        The path to start in
' @param    String  filename    The filename to save
' @return   String              The full path of a filename
' @author   Stefan Thoolen <mail@stefanthoolen.nl>
Public Function SaveFile(ByVal hwnd As Long, Optional ByVal filter As String, Optional ByVal title As String, Optional ByVal path As String, Optional ByVal filename As String) As String
    ' Default values
    If filter = "" Then filter = "Images (*.gif;*.jpg;*.jpeg;*.png)|*.gif;*.jpg;*.jpeg;*.png|HTML (*.htm;*.html)|*.htm;*.html|All files (*.*)|*.*"
    If path = "" Then path = Chr(0)
    If filename = "" Then filename = Chr(0)
    
    ' Prepairs the dialog
    Dim ofn As OPENFILENAME
    With ofn
        .flags = OFN_HIDEREADONLY
        .hwndOwner = hwnd
        .lpstrFilter = Replace(filter, "|", Chr(0)) & Chr(0) & Chr(0)
        .lpstrTitle = title
        .lpstrInitialDir = path
        .lpstrFile = filename & String(260 - Len(filename), 0)
        .nMaxFile = Len(.lpstrFile)
        .lStructSize = Len(ofn)
    End With

    If GetSaveFileNameA(ofn) = 0 Then ' 0 = Returned false
        Dim l As Long
        l = CommDlgExtendedError()
        If l = 0 Then Exit Function ' Cancelled
        MsgBox "CommonDialog Error: CDERR_" & LTrim(Str(l))
        Exit Function
    End If
    
    SaveFile = Left(ofn.lpstrFile, InStr(ofn.lpstrFile, Chr(0)) - 1)
End Function