使用 GetWindowText 将文本框保存到文件中:std::string 到 LPWSTR
Saving a Textbox into file with GetWindowText : std::string to LPWSTR
我尝试了如何将文本框的内容保存到文件的各种代码变体,例如:
std::string str; // same problem with std::wstring
GetWindowTextW(hwndEdit, str.c_str(), 0); // same problem with GetWindowText
std::ofstream file;
file.open("myfile.txt");
file << str;
file.close();
但它们都存在某种字符串变量转换错误:
main.cpp(54) : error C2664: 'GetWindowTextW' : cannot convert parameter 2 from 'const char *' to 'LPWSTR'
如何使用GetWindowText
或GetWindowTextW
?
注意:我事先不知道长度:它可以是 128 个字符以及 1167 个字符或更多。
你在代码中调用未定义的行为 (UB)。我认为这就是你想做的,但只有你确定。
int len = GetWindowTextLengthA(hwndEdit);
if (len > 0)
{
std::vector<char> text(len+1);
GetWindowTextA(hwndEdit, &text[0], len+1);
std::ofstream file("myfile.txt", std::ios::out | std::ios::binary);
file.write(&text[0], len);
}
我手边没有Windows盒子,但我认为这要么是正确的,要么非常接近它。
希望对您有所帮助。
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 真的没有来自 std::string_view 的 std::string 的显式构造函数吗?
- 将C++ std::string 转换为 UTF-16-LE 编码的字符串
- 重载 + 自己的类和 std::string 的运算符
- 如何使用 std::string 作为 QHash 的键?
- 将日语 wstring 转换为 std::string
- 可以从std::string继承以提供类型一致性吗
- 构造函数采用std::string_view与std::string并移动
- 在共享缓冲区内存中创建 ::std::string 对象
- std::string.size() 未知行为
- Valgrind 在 std::string::swap 中报告 SIGILL