// Required include files: #include #include #include #include #include using namespace std; // Note: This function must link with library comdlg32.lib: // Project-->Properties-->ConfigurationProperties-->Linker-->Input // and then click to the right of Additional Dependencies // click the ... button that appears // type the name comdlg32.lib in the text box // and click Apply. // Note: This function requires ordinary characters rather than // Unicode, like this: // Project-->Properties->ConfigurationProperties-->General // and then change the Character Set to // Use Multi-Byte Character Set. // --Michael Main (April 17, 2007) // Function to open a file dialog box and return the name of the // file that the user selects. It works for .txt files only. #define _UNICODE string file_name_from_dialog( ) { string EMPTY = ""; OPENFILENAME ofn; // Struct for opening a file char fn[MAX_PATH+1]; // Space for storing the open file name System::String^ path; // Path of current working directory path = System::IO::Directory::GetCurrentDirectory(); ZeroMemory(&ofn, sizeof(OPENFILENAME)); ZeroMemory(&fn, MAX_PATH+1); ofn.lStructSize = sizeof(OPENFILENAME); ofn.lpstrFilter = "Text files (*.txt)\0*.TXT\0\0"; ofn.lpstrFile = fn; ofn.nMaxFile = MAX_PATH+1; ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST ; if (!GetOpenFileName(&ofn)) return EMPTY; System::IO::Directory::SetCurrentDirectory(path); return fn; } int main() { cout << file_name_from_dialog( ) << endl; return 0; }