Displaying Open File Dialog using WinApi

This article describes sample code that displays an Open dialog box so that a user can choose the directory, and file name of a to open. The process can be done by keyboard or mouse. The sample code first initializes an OPENFILENAME structure, and then calls the GetOpenFileName function to display the dialog box.

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.

This example 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 exist.

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.

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.

Note In the C programming language, a string enclosed in quotation marks is null-terminated.
//#define WIN32_LEAN_AND_MEAN // make sure this is commented out in all code (usually stdafx.h)
#include<windows.h> OPENFILENAME ofn; // common dialog box structure TCHAR szFile[260]={0}; // if using TCHAR macros
// Initialize OPENFILENAME
ZeroMemory(&ofn,sizeof(ofn)); 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

Add comment

Security code