0

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;
}
Sergio
  • 891
  • 9
  • 27
  • 3
    You have to add the `OFN_ENABLEHOOK` flag, and then pass a message handling proc as the `lpfnHook` member of your `ofn` structure. In that message handler, you can position the window wherever you want it. How you retrieve the filename when the dialog is closed is the same as always. – Ken White Apr 19 '19 at 20:09
  • 2
    It's possible, but you have to set a hook and change the position from in the callback. https://stackoverflow.com/questions/29931704/how-to-change-position-of-an-openfilename-dialog-in-windows – Marius Bancila Apr 19 '19 at 20:09

0 Answers0