GetOpenFileName (comdlg32)
Last changed: DragunityMAX-119.247.213.153

.

"Creates an Open dialog box that lets the user specify the drive, directory, and the name of a file or set of files to be opened."

https://docs.microsoft.com/en-us/windows/win32/api/commdlg/nf-commdlg-getopenfilenamea

C# Signature:

[DllImport("comdlg32.dll", SetLastError=true, CharSet = CharSet.Auto)]
static extern bool GetOpenFileName([In, Out] OpenFileName ofn);

VB Signature:

<DllImport("comdlg32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function GetOpenFileName(<[In], Out> ByVal ofn As OpenFileName) As Boolean
End Function

F# Signature:

[<DllImport("comdlg32.dll", SetLastError = true)>]
extern bool GetOpenFileName (OpenFileName& ofn)

User-Defined Types:

OpenFileName

Alternative Managed API:

OpenFileDialog

Notes:

None.

Tips & Tricks:

Please add some!

C# Sample:

class Program
{
    [DllImport("Comdlg32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool GetOpenFileName(ref OpenFileName ofn);

    static void Main(string[] args)
    {
        var ofn = new OpenFileName();
        ofn.lStructSize = Marshal.SizeOf(ofn);
        ofn.lpstrFilter = "All files(*.*)\0\0";
        ofn.lpstrFile = new string(new char[256]);
        ofn.nMaxFile = ofn.lpstrFile.Length;
        ofn.lpstrFileTitle = new string(new char[64]);
        ofn.nMaxFileTitle = ofn.lpstrFileTitle.Length;
        ofn.lpstrTitle = "Open File Dialog...";
        if(GetOpenFileName(ref ofn))
            Console.WriteLine(ofn.lpstrFile);
    }
}

VB Sample:

    ' Copyright
    ' Microsoft Corporation
    ' All rights reserved

    'typedef struct tagOFN {
    '  DWORD     lStructSize;
    '  HWND      hwndOwner;
    '  HINSTANCE     hInstance;
    '  LPCTSTR       lpstrFilter;
    '  LPTSTR    lpstrCustomFilter;
    '  DWORD     nMaxCustFilter;
    '  DWORD     nFilterIndex;
    '  LPTSTR    lpstrFile;
    '  DWORD     nMaxFile;
    '  LPTSTR    lpstrFileTitle;
    '  DWORD     nMaxFileTitle;
    '  LPCTSTR       lpstrInitialDir;
    '  LPCTSTR       lpstrTitle;
    '  DWORD     Flags;
    '  WORD      nFileOffset;
    '  WORD      nFileExtension;
    '  LPCTSTR       lpstrDefExt;
    '  LPARAM    lCustData;
    '  LPOFNHOOKPROC lpfnHook;
    '  LPCTSTR       lpTemplateName;
    '#if (_WIN32_WINNT >= 0x0500)
    '  void *    pvReserved;
    '  DWORD     dwReserved;
    '  DWORD     FlagsEx;
    '#endif // (_WIN32_WINNT >= 0x0500)
    '} OPENFILENAME, *LPOPENFILENAME;

    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> _
    Public Class OpenFileName

        Public structSize As Integer = 0
        Public dlgOwner As IntPtr = IntPtr.Zero
        Public instance As IntPtr = IntPtr.Zero
        Public filter As String = Nothing
        Public customFilter As String = Nothing
        Public maxCustFilter As Integer = 0
        Public filterIndex As Integer = 0
        Public file As String = Nothing
        Public maxFile As Integer = 0
        Public fileTitle As String = Nothing
        Public maxFileTitle As Integer = 0
        Public initialDir As String = Nothing
        Public title As String = Nothing
        Public flags As Integer = 0
        Public fileOffset As Short = 0
        Public fileExtension As Short = 0
        Public defExt As String = Nothing
        Public custData As IntPtr = IntPtr.Zero
        Public hook As IntPtr = IntPtr.Zero
        Public templateName As String = Nothing
        Public reservedPtr As IntPtr = IntPtr.Zero
        Public reservedInt As Integer = 0
        Public flagsEx As Integer = 0

    End Class 'OpenFileName

    Public Class LibWrap
        'BOOL GetOpenFileName(LPOPENFILENAME lpofn);
        Declare Auto Function GetOpenFileName Lib "Comdlg32.dll" ( _
        <[In](), Out()> ByVal ofn As OpenFileName) As Boolean
    End Class 'LibWrap

    Private Function ShowOpen(Optional ByVal filter As String = ("All files" & ChrW(0) & "*.*" & ChrW(0)), _    
                  Optional ByVal title As String = "Open File Dialog...", _
                  Optional ByVal defext As String = "*", _
                  Optional ByVal path As String = "C:\") As String

        Try
        Dim ofn As New OpenFileName

        ofn.structSize = Marshal.SizeOf(ofn)
        ofn.filter = filter
        ofn.file = New String(New Char(256) {})
        ofn.maxFile = ofn.file.Length
        ofn.fileTitle = New String(New Char(64) {})
        ofn.maxFileTitle = ofn.fileTitle.Length
        ofn.initialDir = path
        ofn.title = title
        ofn.defExt = defext

        If LibWrap.GetOpenFileName(ofn) Then
            Console.WriteLine("Selected file with full path: {0}", ofn.file)
            Console.WriteLine("Selected file name: {0}", ofn.fileTitle)
            Console.WriteLine("Offset from file name: {0}", ofn.fileOffset)
            Console.WriteLine("Offset from file extension: {0}", ofn.fileExtension)

            Return ofn.file
        End If
        Catch ex As Exception
        Debug.Assert(False)
        Return System.String.Empty
        End Try

    End Function

F# Sample

type Flags =
   | OFN_ALLOWMULTISELECT = 0x00000200
   | OFN_CREATEPROMPT = 0x00002000
   | OFN_DONTADDTORECENT = 0x02000000
   | OFN_ENABLEHOOK = 0x00000020
   | OFN_ENABLEINCLUDENOTIFY = 0x00400000
   | OFN_ENABLESIZING = 0x00800000
   | OFN_ENABLETEMPLATE = 0x00000040
   | OFN_ENABLETEMPLATEHANDLE = 0x00000080
   | OFN_EXPLORER = 0x00080000
   | OFN_EXTENSIONDIFFERENT = 0x00000400
   | OFN_FILEMUSTEXIST = 0x00001000
   | OFN_FORCESHOWHIDDEN = 0x10000000
   | OFN_HIDEREADONLY = 0x00000004
   | OFN_LONGNAMES = 0x00200000
   | OFN_NOCHANGEDIR = 0x00000008
   | OFN_NODEREFERENCELINKS = 0x00100000
   | OFN_NOLONGNAMES = 0x00040000
   | OFN_NONETWORKBUTTON = 0x00020000
   | OFN_NOREADONLYRETURN = 0x00008000
   | OFN_NOTESTFILECREATE = 0x00010000
   | OFN_NOVALIDATE = 0x00000100
   | OFN_OVERWRITEPROMPT = 0x00000002
   | OFN_PATHMUSTEXIST = 0x00000800
   | OFN_READONLY = 0x00000001
   | OFN_SHAREAWARE = 0x00004000
   | OFN_SHOWHELP = 0x00000010

[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type OpenFileName =
   val mutable lStructSize: int
   val mutable hwndOwner: nativeint
   val mutable hInstance: nativeint
   val mutable lpstrFilter: string
   val mutable lpstrCustomFilter: string
   val mutable nMaxCustFilter: int
   val mutable nFilterIndex: int
   val mutable lpstrFile: string
   val mutable nMaxFile: int
   val mutable lpstrFileTitle: string
   val mutable nMaxFileTitle: int
   val mutable lpstrInitialDir: string
   val mutable lpstrTitle: string
   val mutable Flags: Flags
   val mutable nFileOffset: int16
   val mutable nFileExtension: int16
   val mutable lpstrDefExt: string
   val mutable lCustData: nativeint
   val mutable lpfnHook: nativeint
   val mutable lpTemplateName: string
   val mutable pvReserved: nativeint
   val mutable dwReserved: int
   val mutable FlagsEx: int

let mutable ofn = OpenFileName ()
ofn.lStructSize <- Marshal.SizeOf (ofn)
//The first character of this buffer must be NULL if initialization is not necessary.
ofn.lpstrFile <- Char.MinValue.ToString () + new string (' ', 256)
ofn.nMaxFile <- ofn.lpstrFile.Length
ofn.lpstrFileTitle <- new string (' ', 64)
ofn.nMaxFileTitle <- ofn.lpstrFileTitle.Length
ofn.Flags <- Flags.OFN_FILEMUSTEXIST ||| Flags.OFN_PATHMUSTEXIST

if (GetOpenFileName (&ofn)) then
   Choice1Of2 ofn.lpstrFile
else
   Choice2Of2 (sprintf "GetOpenFileName failed with the error code: %d" (Marshal.GetLastWin32Error ()))

Sample code tiny c OR gcc Cygwin:

tcc (http://bellard.org/tcc/) command line to compile:

tcc -lcomdlg32 openfilename.c

./openfilename.exe is 2,048 bytes !!!

gcc (under cygwin) command line to compile:

gcc -Wall -Wl,--enable-stdcall-fixup -mnop-fun-dllimport -mwindows getopenfilename.c

./a.exe is 61,414 bytes !!!

#include <windows.h>

// tinycc: pull info from CYGWIN header /usr/include/w32api/commdlg.h
#ifdef __TINYC__
#define OFN_READONLY 0x1
#define OFN_OVERWRITEPROMPT 0x2
#define OFN_HIDEREADONLY 0x4
#define OFN_NOCHANGEDIR 0x8
#define OFN_SHOWHELP 0x10
#define OFN_ENABLEHOOK 0x20
#define OFN_ENABLETEMPLATE 0x40
#define OFN_ENABLETEMPLATEHANDLE 0x80
#define OFN_NOVALIDATE 0x100
#define OFN_ALLOWMULTISELECT 0x200
#define OFN_EXTENSIONDIFFERENT 0x400
#define OFN_PATHMUSTEXIST 0x800
#define OFN_FILEMUSTEXIST 0x1000
#define OFN_CREATEPROMPT 0x2000
#define OFN_SHAREAWARE 0x4000
#define OFN_NOREADONLYRETURN 0x8000
#define OFN_NOTESTFILECREATE 0x10000
#define OFN_NONETWORKBUTTON 0x20000
#define OFN_NOLONGNAMES 0x40000
#define OFN_EXPLORER 0x80000
#define OFN_NODEREFERENCELINKS 0x100000
#define OFN_LONGNAMES 0x200000
#define OFN_ENABLEINCLUDENOTIFY 0x400000
#define OFN_ENABLESIZING 0x800000
#define OFN_DONTADDTORECENT 0x2000000
#define OFN_FORCESHOWHIDDEN 0x10000000
#define OFN_EX_NOPLACESBAR 0x1
#define OFN_SHAREFALLTHROUGH 2
#define OFN_SHARENOWARN 1
#define OFN_SHAREWARN 0

typedef UINT_PTR (CALLBACK *LPOFNHOOKPROC) (HWND,UINT,WPARAM,LPARAM);

typedef struct tagOFNA {
     DWORD lStructSize;
     HWND hwndOwner;
     HINSTANCE hInstance;
     LPCSTR lpstrFilter;
     LPSTR lpstrCustomFilter;
     DWORD nMaxCustFilter;
     DWORD nFilterIndex;
     LPSTR lpstrFile;
     DWORD nMaxFile;
     LPSTR lpstrFileTitle;
     DWORD nMaxFileTitle;
     LPCSTR lpstrInitialDir;
     LPCSTR lpstrTitle;
     DWORD Flags;
     WORD nFileOffset;
     WORD nFileExtension;
     LPCSTR lpstrDefExt;
     LPARAM lCustData;
     LPOFNHOOKPROC lpfnHook;
     LPCSTR lpTemplateName;
     void *pvReserved;
     DWORD dwReserved;
     DWORD FlagsEx;
} OPENFILENAMEA,*LPOPENFILENAMEA;

#define OPENFILENAME OPENFILENAMEA
#define LPOPENFILENAME LPOPENFILENAMEA
#define GetOpenFileName GetOpenFileNameA

#endif

#ifdef __CYGWIN__
#include <commdlg.h>
#endif

// below adapted from: https://www.daniweb.com/software-development/cpp/code/217307/a-simple-getopenfilename-example

int main(int argc, char **argv) {
    char szFile[100];
    OPENFILENAME ofn;
    memset(&ofn, 0, sizeof (ofn));
    ofn.lStructSize = sizeof (ofn);
    ofn.hwndOwner = NULL;
    ofn.lpstrFile = szFile;
    ofn.lpstrFile[0] = '\0';
    ofn.nMaxFile = sizeof (szFile);
    ofn.lpstrFilter = "All\0*.*\0Text\0*.TXT\0";
    ofn.nFilterIndex = 1;
    ofn.lpstrFileTitle = NULL;
    ofn.nMaxFileTitle = 0;
    ofn.lpstrInitialDir = NULL;
    ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
    int i = GetOpenFileName(&ofn);
    return(i);
}

Contributed by John Refling

Documentation