请教如何用C++,弹出选择文件窗口,并在控制台打印已选文件路径

如题,现在使用VC2017,听说可以使用OpenFileDialog,刚入门小白,请问具体需要怎么用,感谢各位大神

这是原生C++的做法:

// Q694481_Win32.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <windows.h>
#include <Commdlg.h>
#include <stdio.h>

OPENFILENAME ofn;
char szFile[300];

int main()
{
    ZeroMemory(&ofn, sizeof(ofn));
    ofn.lStructSize = sizeof(ofn);
    ofn.hwndOwner = NULL;
    ofn.lpstrFile = (LPWSTR)szFile;
    ofn.lpstrFile[0] = '\0';
    ofn.nMaxFile = sizeof(szFile);
    ofn.lpstrFilter = L"All\0*.*\0Text\0*.TXT\0";
    ofn.nFilterIndex = 1;
    ofn.lpstrFileTitle = NULL;
    ofn.nMaxFileTitle = 0;
    ofn.lpstrInitialDir = NULL;
    ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
    if (GetOpenFileName(&ofn))
    {
        wprintf(L"%s\n", ofn.lpstrFile);
    }
    else
    {
        printf("user cancelled\n");
    }
    return 0;
}

OpenFileDialog是.net的库,你必须创建一个C++ CLR的程序

 // Q694481.cpp : main project file.

#include "stdafx.h"

using namespace System;
using namespace System::Windows::Forms;

[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
    OpenFileDialog^ openFileDialog = gcnew OpenFileDialog;
    if (openFileDialog->ShowDialog() == System::Windows::Forms::DialogResult::OK)
    {
        Console::WriteLine(openFileDialog->FileName);
    }
    Console::ReadLine();
}

图片说明

图片说明