Sunday, 30 March 2014

Using GetOpenFileName

GetOpenFileName displays the "standard" File Open dialog box on Windows, allowing users to choose a file.

To use this function, Commdlg.h (and Windows.h) should be included. Declare an OPENFILENAME structure and at minimum set the following:

OPENFILENAME ofn;

ofn.lStructSize = sizeof(OPENFILENAME);
// Required: the size of the structure

ofn.hwndOwner = hwnd;
// The handle of the window that owns this dialog

static char szFileName[_MAX_PATH];
ofn.lpstrFile = szFileName;
// Where to put the path of the selected file
ofn.nMaxFile = _MAX_PATH;

static char szTitleName[_MAX_FNAME + _MAX_EXT];
ofn.lpstrFileTitle = szTitleName;
// Where to put the name of the file
ofn.nMaxFileTitle = _MAX_FNAME + _MAX_EXT;


Then, pass the OPENFILENAME structure to the function GetOpenFileName:

bool status = GetOpenFileName(&ofn);

If the function was successful, status will be true, otherwise false (e.g. the user clicked the cancel button).

Noteworthy: GetOpenFileName is now legacy. Instead of using this from the Common Dialog Box Library, a newer alternative is available: the Common Item Dialog API. The alternative fits more with the look and feel of Windows Vista and above. More on this in a future post.

No comments:

Post a Comment