Search code examples
vb6fileopendialog

Opening a File Dialog from within a class module in vb6


I want to know how can we open a file dialog from withing a class module in vb6. I know how to do in forms, but I have to open it from within a class module.


Solution

  • Have a look at the API below:

    Private Declare Function GetOpenFileName Lib "comdlg32.dll" Alias _
        "GetOpenFileNameA" (pOpenfilename As OPENFILENAME) As Long
    

    Here's a sample of it in use:

        Private Declare Function GetOpenFileName Lib "comdlg32.dll" Alias _
            "GetOpenFileNameA" (pOpenfilename As OPENFILENAME) As Long
    
        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
    
        Private Function FileOpenDialog()
            Dim sFilter As String
    
            OpenFile.lStructSize = Len(OpenFile)
            sFilter = "Text Files (*.txt)" & Chr(0) & "*.TXT" & Chr(0)
            OpenFile.lpstrFilter = sFilter
            OpenFile.nFilterIndex = 1
            OpenFile.lpstrFile = String(257, 0)
            OpenFile.nMaxFile = Len(OpenFile.lpstrFile) - 1
            OpenFile.lpstrFileTitle = OpenFile.lpstrFile
            OpenFile.nMaxFileTitle = OpenFile.nMaxFile
            OpenFile.lpstrInitialDir = "C:\"
            OpenFile.lpstrTitle = "Select File"
            OpenFile.flags = 0
    
            lReturn = GetOpenFileName(OpenFile)
    
    
        End Function