Source Code: File Dialogs

This will open the open file and save file dialog.

#include <iostream>
#include <windows.h>
 
using namespace std;
 
OPENFILENAME ofn; // Common dialog box structure.
char FileBuf[260]; // Buffer for selected file name.
HWND hwnd; // Owner window.
HANDLE hf; // File handle.
 
inline void dialog_open()
{
    ZeroMemory(&ofn, sizeof(ofn));
    ofn.lStructSize = sizeof(ofn);
    ofn.hwndOwner = hwnd;
    ofn.lpstrFile = FileBuf;
    ofn.nMaxFile = sizeof(FileBuf);
    ofn.lpstrFilter = "Text Files (*.txt)\0*.txt\0All Files\0*.*\0";
    ofn.nFilterIndex = 2;
    ofn.lpstrDefExt = "txt";
    ofn.lpstrFileTitle = NULL;
    ofn.nMaxFileTitle = 0;
    ofn.lpstrInitialDir = NULL;
    ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
    GetOpenFileName(&ofn);
    return;
}
 
inline void dialog_save()
{
    ZeroMemory(&ofn, sizeof(ofn));
    ofn.lStructSize = sizeof(ofn);
    ofn.hwndOwner = hwnd;
    ofn.lpstrFile = FileBuf;
    ofn.nMaxFile = sizeof(FileBuf);
    ofn.lpstrFilter = "Text Files (*.txt)\0*.txt\0All Files\0*.*\0";
    ofn.nFilterIndex = 2;
    ofn.lpstrDefExt = "txt";
    ofn.lpstrFileTitle = NULL;
    ofn.nMaxFileTitle = 0;
    ofn.lpstrInitialDir = NULL;
    ofn.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT;
    GetSaveFileName(&ofn);
    return;
}
 
int main()
{
    int ans;
    cout << "Press 1 to open the open file dialog or 2 to open the save file sialog." << endl;
    cin >> ans;
    switch (ans)
    {
        case 1:
        dialog_open();
        break;
        case 2:
        dialog_save();
        break;
        default:
        break;
    }
    cout << "Path: " << FileBuf << endl;
    return 0;
}
Categories: Source Code
page_revision: 4, last_edited: 1245587890|%e %b %Y, %H:%M %Z (%O ago)