【问题标题】:Saving a Textbox into file with GetWindowText : std::string to LPWSTR使用 GetWindowText 将文本框保存到文件中:std::string 到 LPWSTR
【发布时间】:2015-01-05 13:11:10
【问题描述】:

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

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 字符或更多。

【问题讨论】:

  • 您将宽文本保存到 (a) 一个窄字符串中,该字符串 (b) 是只读的,并且 (c) 长度为零,但 所有 都是错误的。而且你可以提前知道长度,看; GetWindowTextLengthAGetWindowTextA 用于可能满足您需求的狭窄功能。
  • 感谢@WhozCraig,我尝试std::string str (GetWindowTextLengthA(hwndEdit)); 创建一个可以包含正确长度的字符串,但仍然存在一些错误。你想知道答案吗?我正在浏览许多/字符串教程文档,但无法完成这项工作。

标签: c++ winapi stdstring


【解决方案1】:

您正在代码中调用未定义的行为 (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 盒子,但我认为这要么是正确的,要么非常接近。

希望对你有帮助。

【讨论】:

  • 谢谢!不幸的是,我得到了error C2039: 'vector' : is not a member of 'std'。顺便问一下,什么是“UB”?
  • @Basj #include &lt;vector&gt; 在您的包含列表中,而 UB 表示 未定义的行为
  • 好的include。它几乎可以工作,但输出文件包含奇怪的内容:426f 6e6a 6f75 7220 7173 646b 6a71 640d 0d0a 7173 6473 716b 6a64 716b 6864 7371 00...you're invoking undefined behaviour 是什么意思?
  • @Basj Heh,我很害怕。您是否在编辑框中转储 Unicode 文本?如果是这样,您可以在写入之前转换为 UTF-8,但代码要复杂得多。在处理 Unicode 到 UTF-8 的翻译时,SO 有多个答案。 (或者只是将文件写为 unicode,如果这是一个选项)。
  • 我不知道,我只是用键盘写文字。这是完整的代码:github.com/josephernest/NeverForget/blob/master/src/… ...我完全不知道在哪里/为什么/何时在此代码中添加 Unicode 处理:(
猜你喜欢
  • 1970-01-01
  • 2014-10-03
  • 2018-05-18
  • 1970-01-01
  • 2018-09-12
  • 1970-01-01
  • 1970-01-01
  • 2012-09-27
  • 1970-01-01
相关资源
最近更新 更多