I would like to display a common dialog at desktop center, calling GetOpenFileName() from a console program.
From the Open File Name dialog, I want to get just the name of the selected file.
Is there any way to do this?

#include <iostream>
#include <string>
#include <windows.h>
#include <CommDlg.h>
#include <fstream>

using namespace std;

std::string OpenTxtFileDialog(HWND hWnd)
{
    std::string fileName;

    char szFile[260];
    OPENFILENAME ofn = {0};
    ofn.lStructSize = sizeof(ofn);
    ofn.hwndOwner = hWnd;
    ofn.lpstrFile = szFile;
    ofn.lpstrFile[0] = '\0';
    ofn.nMaxFile = sizeof(szFile);
    ofn.lpstrFilter = "txt\0*.txt\0";
    ofn.nFilterIndex = 1;
    ofn.lpstrFileTitle = NULL;
    ofn.nMaxFileTitle = 0;
    ofn.lpstrInitialDir = NULL;
    ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
    if(GetOpenFileName(&ofn))
    {
       fileName = szFile;
    }
    return fileName;
}

int main()
{
    std::string path;

    HWND hDesktop = GetDesktopWindow();

    path = OpenTxtFileDialog(hDesktop);

    cout << path << endl;

    std::ifstream infile(path.c_str(), ios::in);

    infile.close();

    return 0;
}

0 Answers