I've been looking at common dialog boxes, specifically how to open a file of a users choice.
I'd like to have a function that I can call that returns me the path to the file the user chose.
Here's what I have so far:
Code:
char* openFile()
{
OPENFILENAME ofn; // common dialog box structure
char szFile[MAX_PATH]; // buffer for file name
// Initialize OPENFILENAME
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = NULL;
ofn.lpstrFile = szFile;
// Set lpstrFile[0] to '\0' so that GetOpenFileName does not
// use the contents of szFile to initialize itself.
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = MAX_PATH;
ofn.lpstrFilter = "All\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
// Display the Open dialog box.
if (GetOpenFileName(&ofn))
{
MessageBox(NULL, szFile ,"File Chosen", MB_OK); //This Line is important Call it line X
return szFile;
}
return "Error file choosen doesn't exist or no file was chosen";
}
Called from main:
Code:
int main()
{
char result[MAX_PATH];
strcpy( result, openFile() );
MessageBox(NULL, result ,"File Chosen", MB_OK);
}
This works just fine except for one little problem. If I remove the message box at line X then the open file dialog box never opens and the message box in main pops up empty. It's almost as if the message box in line x pauses code execution so a user can choose a file.
Thanks for reading