!program fileopen
integer function Open_File(file_spec, w_title, Intial_Directory)

use comdlg32
use user32 ! Interface for GetForegroundWindow
implicit none

! Declare structure used to pass and receive attributes
!
type(T_OPENFILENAME) ofn

! Declare filter specification.  This is a concatenation of
! pairs of null-terminated strings.  The first string in each pair
! is the file type name, the second is a semicolon-separated list
! of file types for the given name.  The list ends with a trailing
! null-terminated empty string.
!
character(*),parameter :: filter_spec = &
  "Data Files"C//"*.dat"C// &
  "Text Files"C//"*.txt"C// &
  "Fortran Files"C//"*.f90;*.f"C// &
  ""C

! Declare string variable to return the file specification.
! Initialize with an initial filespec, if any - null string
! otherwise
!
!character(512) :: file_spec = ""C
character(max_path) :: file_spec     !""C
character(max_path) Intial_Directory
integer status,ilen

character(80) :: w_title


ofn%lStructSize = SIZEOF(ofn)
ofn%hwndOwner = GetForegroundWindow()
ofn%hInstance = NULL  ! For Win32 applications, you
                      ! can set this to the appropriate
                      ! hInstance
                      !
ofn%lpstrFilter = loc(filter_spec)
ofn%lpstrCustomFilter = NULL
ofn%nMaxCustFilter = 0
ofn%nFilterIndex = 1 ! Specifies initial filter value
ofn%lpstrFile = loc(file_spec)
ofn%nMaxFile = sizeof(file_spec)
ofn%nMaxFileTitle = 0
!ofn%lpstrInitialDir = NULL  ! Use Windows default directory
ofn%lpstrInitialDir = loc(Intial_Directory)

!ofn%lpstrTitle = loc(""C)
ofn%lpstrTitle = loc(w_title)

ofn%Flags = OFN_PATHMUSTEXIST
ofn%lpstrDefExt = loc("dat"C)   !("txt"C)
ofn%lpfnHook = NULL
ofn%lpTemplateName = NULL

! Call GetOpenFileName and check status
! 
status = GetOpenFileName(ofn)

Open_File =status

if (status .eq. 0) then
  type *,'No file name specified'
else
  ! Get length of file_spec by looking for trailing NUL
  ilen = INDEX(file_spec,CHAR(0))
  type *,'Selected File: ',file_spec(1:ilen-1)
  ! Example of how to see if user said "Read Only"
  !  
end if

END

