[API]
tOpenType
RtlMoveMemory
GetOpenFileNameA
GetOpenFileNameW
GetSaveFileNameA
GetSaveFileNameW

[INCLUDE]
PokeL
LocalAllocFromString
PeekS

[DEFINE]
Public Const LoadSingleFile As Long = &H81004
Public Const LoadMultipleFiles As Long = &H81204
Public Const SaveSingleFile As Long = &H80006

[CODE]
Public Function CommonDLG_OpenFiles(ByVal hWnd As Long, ByVal Filters As String, ByVal FileMode As Long, ByVal DlgCaption As String, Optional ByVal InitDir As String) As String
  Dim xLong1 As Long
    
  Dim xType1 As tOpenType
  Const DataSize As Long = 32760&
  Const DataSizeW As Long = (DataSize) * 2&
    
  xLong1 = (1& - CLng(IsUnicode)) * (DataSize + 2&)
  With xType1
    .lpstrFilter = LocalAllocFromString(Filters & vbNullChar)
    .lpstrTitle = LocalAllocFromString(DlgCaption)
    .nFilterIndex = 1
    .lpstrFile = LocalAlloc(0&, xLong1)
    Call PokeL(.lpstrFile, 0&)
    .nMaxFile = DataSize
    .lpstrFileTitle = LocalAlloc(0&, xLong1)
    .nMaxFileTitle = DataSize
    .lStructSize = 76&
    .hWndOwner = hWnd
    .hInstance = App.hInstance
    If Not Len(InitDir) = 0& Then
      .lpstrInitialDir = LocalAllocFromString(InitDir)
      End If

    hWnd = InStr(Filters, vbNullChar) + 1&
    xLong1 = InStr(hWnd, Filters & vbNullChar, vbNullChar)
    If Not hWnd = 1& Then
      Filters = Mid(Filters, hWnd, InStr(hWnd, Filters & vbNullChar, vbNullChar) - hWnd)
      If Not Filters = "" Then .lpstrDefExt = LocalAllocFromString(Filters)
      End If
    .Flags = FileMode
      
    If FileMode = SaveSingleFile Then
      If IsUnicode Then
        xLong1 = GetSaveFileNameW(xType1)
        Else
        xLong1 = GetSaveFileNameA(xType1)
        End If
      ElseIf IsUnicode Then
      xLong1 = GetOpenFileNameW(xType1)
      Else
      xLong1 = GetOpenFileNameA(xType1)
      End If
    If Not xLong1 = 0& Then
      If FileMode = LoadMultipleFiles Then
        CommonDLG_OpenFiles = String(DataSize, vbNullChar)
        If IsUnicode Then
          Call RtlMoveMemory(ByVal StrPtr(CommonDLG_OpenFiles), ByVal xType1.lpstrFile, DataSizeW)
          Else
          Call RtlMoveMemory(ByVal CommonDLG_OpenFiles, ByVal xType1.lpstrFile, DataSize)
          End If
        xLong1 = InStr(CommonDLG_OpenFiles, vbNullChar & vbNullChar)
        If xLong1 = 0& Then
          CommonDLG_OpenFiles = ""
          Else
          CommonDLG_OpenFiles = Left(CommonDLG_OpenFiles, xLong1 + 1&)
          End If
        Else
        CommonDLG_OpenFiles = PeekS(xType1.lpstrFile)
        End If
      End If
    TryFree .lpstrFilter
    TryFree .lpstrTitle
    TryFree .lpstrFile
    TryFree .lpstrFileTitle
    TryFree .lpstrInitialDir
    TryFree .lpstrDefExt
    End With
  End Function
  
Private Sub TryFree(ByVal ptrMem As Long)
  If Not ptrMem = 0& Then Call LocalFree(ptrMem)
  End Sub
