读取文件并将其添加到文本框中:字符串转换问题

Read a file and add it to a textbox : string conversion issue

本文关键字:字符串 问题 转换 文本 文件 添加 读取      更新时间:2023-10-16

我使用:

std::ifstream t("myfile.txt");
std::string str((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
SendMessage(hwndEdit, WM_SETTEXT, 0, (LPARAM) str); 

myfile.txt的内容读入使用以下命令创建的文本框中:

HWND hwndEdit = CreateWindowEx(0, L"EDIT", NULL, WS_CHILD | WS_VISIBLE, ...)

如何解决此错误?

main.cpp(34) : error C2440: 'type cast' : cannot convert from 'std::string' to 'LPARAM' 
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

我了解WM_SETTEXT lparam 的文档应该是

指向以 null 结尾的字符串(即窗口文本)的指针。

这意味着 C 样式字符串,一个 char* 变量。你可以尝试传递str.c_str()一个lParam。

LPARAM定义为:typedef LONG_PTR LPARAM

所以基本上它需要一个指向通过消息传递的一些数据的指针。
然后接收方可以根据消息类型对其进行解释。

如果要传递字符串,则应传递其基础c_str()
当然,请确保该字符串在消息到达之前有效:

SendMessage(hwndEdit, WM_SETTEXT, 0, (LPARAM) str.c_str());