c++ - Winapi GetOpenFileName 扩展过滤器不工作

标签 c++ function winapi std getopenfilename

我正在尝试将文件的扩展名过滤器应用于文件的选择对话框。

这种方式有效:

ofn.lpstrFilter =   
"(*.exe) Windows Executable\0*.exe\0"
"(*.ini) Windows Initialization file \0*.ini\0"
"(*.dll) Dynamic Link Library \0*.dll\0"
"(*.lib) Windows Library file \0*.lib\0"
"(*.conf) Windows Configuration file \0*.conf\0";

enter image description here

但是当我通过参数动态分配扩展过滤器时,它失败了,过滤器没有出现在组合框中:

LPCSTR filter = (LPCSTR)extFilter; //Contains string "bmp"

stringstream s;
s << "(*.exe) Windows Executable\0" << "*." << filter << "\0";
string ffilter = s.str();
ofn.lpstrFilter = ffilter.c_str();

enter image description here

我假设问题出在字符串转换中,但无法弄清楚。

最佳答案

这一行:

s << "(*.exe) Windows Executable\0" << "*." << filter << "\0";

正在传递以 null 结尾的 char*字符串到 operator<<() ,因此在运行时实际上与这段代码表现相同:

s << "(*.exe) Windows Executable" << "*." << filter << "";

空值永远不会进入 s .

要正确插入空值,您需要将它们分配给 stringstream作为个人char值而不是 char*值(value)观:

s << "(*.exe) Windows Executable" << '\0' << "*." << filter << '\0';

此外,您正在进行类型转换 extFilter是可疑的。如果您必须这样做才能消除编译器错误,那么 extFilter不是兼容的数据类型,类型转换隐藏了代码中的错误。摆脱类型转换:

LPCSTR filter = extFilter; //Contains string "bmp"

如果代码无法编译,那么你做错了什么,需要正确修复它。

另一方面,如果extFilter是一个空终止 char字符串开头,在将其传递给 operator<<() 之前不需要将其分配给变量:

s << "(*.exe) Windows Executable" << '\0' << "*." << extFilter << '\0';

关于c++ - Winapi GetOpenFileName 扩展过滤器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34092427/

相关文章:

javascript - 将类似的点击事件操作转换为函数?

c++ - Windows 操作系统多久可以从唤醒计时器中唤醒?

c# - 始终在桌面上保留表格(无 Win+D 效果)

C++ OBJ文件解析器

c++ - 什么是对象切片?

c - 无法通过函数向数组添加项目 (C)

c++ - 为什么不能向组合框添加字符串? VS C++

c++ - 如何使用cmake在linux下构建Qt项目

c++ - 使用 SFTP 和 Pageant 身份验证更新服务器文件夹

c++ - 为什么 std::bind 在这个例子(成员函数)中没有占位符就不能工作?