Skip to content

Open File Dialog Helper

A C helper function that wraps GetOpenFileName with file-type filters, a default extension, and an initial directory.

Published Jun 21, 1999

A ready-to-paste wrapper around GetOpenFileName for when you want the standard Windows open dialog without filling in all fifteen OPENFILENAME fields yourself every time. It takes an owner window and a buffer (which doubles as the initial filename and comes back filled with the chosen path), sets up a three-entry filter string (log files, text files, everything), a default extension, a title, and an initial directory, and returns the API's boolean result. The flags - OFN_EXPLORER | OFN_LONGNAMES | OFN_PATHMUSTEXIST - give you the Explorer-style UI, full long paths, and no phantom filenames.

//////////////////////////////////////////////////////////////////////////

int OpenFileDialog (HWND xHandle, char *xFileName)
{
	char FileName[2048];
	int ReturnValue = 0;
	OPENFILENAME OFN;

	sprintf(FileName,"%s",xFileName);

	OFN.lpstrCustomFilter = NULL;
	OFN.nMaxCustFilter	  = 0;
	OFN.lpstrFileTitle	  = NULL;
	OFN.nMaxFileTitle	  = 0;

	OFN.lpstrFilter 	  = "Log-Files\0*.Log\0Text-Files\0*.txt\0All-Files\0*.*\0\0";
	OFN.lpstrDefExt 	  = "*.log";
	OFN.lpstrTitle		  = "My Title";
	OFN.lpstrInitialDir   = "C:\\";

	OFN.lStructSize 	  = sizeof(OFN);
	OFN.hwndOwner		  = xHandle;
	OFN.nFilterIndex	  = 1;
	OFN.lpstrFile		  = FileName;
	OFN.nMaxFile		  = sizeof(FileName);
	OFN.Flags			  = OFN_EXPLORER + OFN_LONGNAMES + OFN_PATHMUSTEXIST;

	ReturnValue = GetOpenFileName(&OFN);

	sprintf(xFileName,"%s",FileName);

	return ReturnValue;
}

The filter string is the part people always get wrong: it is a sequence of display name\0pattern\0 pairs terminated by an extra \0. For new code the wide-character GetOpenFileNameW or the Vista+ IFileOpenDialog COM interface are preferable, but this remains the fastest way to drop a working picker into a legacy AANSI Win32 app.

An unhandled error has occurred. Reload 🗙