Displaying Open File Dialog using WinApi
This article answers the question How to display Open File Dialog in the C++ program? Further, we will show the sample code that displays an Open dialog box so that a user can choose the directory and a file name of a to open. The whole program is built on Windows API and can run on Windows 10, Windows 8, Windows 7, and even Windows XP.
The GetOpenFileName function returns TRUE if the user clicks the OK button and the specified path and file name exist. In this case, the buffer pointed to by the lpstrFile member contains the path and file name. The sample code uses this information in a call to the function to open the file.
In this example, the lpstrFilter member is a pointer to a buffer that specifies two file name filters that the user can select to limit the file names that are displayed. The buffer contains a double-null terminated array of strings in which each pair of strings specifies a filter. The nFilterIndex member specifies that the first pattern is used when the dialog box is created.
The sample code sets the OFN_PATHMUSTEXIST and OFN_FILEMUSTEXIST flags in the Flags member. These flags cause the dialog box to verify, before returning, that the path and file name specified by the user actually exists.
Although this example does not set the OFN_EXPLORER flag, it still displays the default Explorer-style Open dialog box. However, if you want to provide a hook procedure or a custom template and you want the Explorer user interface, you must set the OFN_EXPLORER flag.
// make sure WIN32_LEAN_AND_MEAN is commented out in all code (usually stdafx.h)
//#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <string.h>
// common dialog box structure, setting all fields to 0 is important
OPENFILENAME ofn = {0};
TCHAR szFile[260]={0};
// Initialize remaining fields of OPENFILENAME structure
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hWnd;
ofn.lpstrFile = szFile;
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = _T("All\0*.*\0Text\0*.TXT\0");
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
if(GetOpenFileName(&ofn) == TRUE)
{
// use ofn.lpstrFile here
}