c++ - 使用带有多选标志的 GetOpenFileName() 时如何获取所选文件的列表?

标签 c++ windows winapi visual-c++

我试过谷歌搜索,但人们似乎遇到了同样的问题:我们无法获得所选文件的列表。

这是一段简单的工作代码,与我使用的代码类似:

OPENFILENAME ofn = { sizeof ofn };
wchar_t file[1024];
file[0] = '\0';
ofn.lpstrFile = file;
ofn.nMaxFile = 1024;
ofn.Flags = OFN_ALLOWMULTISELECT | OFN_EXPLORER;
GetOpenFileName(&ofn);

我实际上如何获得我选择的文件名?目前我只能在没有 OFN_ALLOWMULTISELECT 标志的情况下让它工作,所以它会将一个选定的文件名返回到 ofn.lpstrFile 中。我试图打印出该结构内的所有字符串变量,但一无所获。它只显示所选文件的主文件夹。

最佳答案

看起来 ofn.lpstrFile 包含所有文件名,以 NULL 分隔并以另一个 NULL 结尾(实际上以空字符串结尾)。

If the OFN_ALLOWMULTISELECT flag is set and the user selects multiple files, the buffer contains the current directory followed by the file names of the selected files. For Explorer-style dialog boxes, the directory and file name strings are NULL separated, with an extra NULL character after the last file name. For old-style dialog boxes, the strings are space separated and the function uses short file names for file names with spaces. You can use the FindFirstFile function to convert between long and short file names. If the user selects only one file, the lpstrFile string does not have a separator between the path and file name.

来自 MSDN .

解析内容的可能实现是;

wchar_t* str = ofn.lpstrFile;
std::wstring directory = str;
str += ( directory.length() + 1 );
while ( *str ) {
  std::wstring filename = str;
  str += ( filename.length() + 1 );
  // use the filename, e.g. add it to a vector
}

关于c++ - 使用带有多选标志的 GetOpenFileName() 时如何获取所选文件的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26317556/

相关文章:

asp.net - 如何将 VB.NET Web 应用程序发布到我的 Azure Windows 2012 R2 VM

c - 如何不阻止设备被弹出/安全移除?

c++ - 在调用函数的范围内构造返回对象

c++ - C++ 编译器中的可变长度数组 (VLA)

c++ - 从 WPF 窗口内的托管 DLL 启动 WNDProc

c++ - 使用 C++ 检测进程崩溃的最佳方法是什么

c++ - WinAPI 将 FILETIME 格式化为带有日期和/或时间的本地化字符串

c++ - 获取指向虚方法的指针?

windows - 如何使用批处理脚本最好通过 WINDOWS 中的端口 80 终止 CLOSE_WAIT 状态进程

windows - Visual Studio 调试期间的浏览器窗口大小