使用 GetWindowText 将文本框保存到文件中:std::string 到 LPWSTR

Saving a Textbox into file with GetWindowText : std::string to LPWSTR

本文关键字:std string LPWSTR 存到文件 GetWindowText 文本 使用      更新时间:2023-10-16

我尝试了如何将文本框的内容保存到文件的各种代码变体,例如:

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'

如何使用GetWindowTextGetWindowTextW

注意:我事先不知道长度:它可以是 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盒子,但我认为这要么是正确的,要么非常接近它。

希望对您有所帮助。