How to send a string via PostMessage?(如何通过PostMessage发送字符串?)
本文介绍了如何通过PostMessage发送字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的应用程序中,我希望从不同的线程向对话框发送消息。 我想将std::Exception派生类引用传递给对话框。如下所示:
try {
//do stuff
}
catch (MyException& the_exception) {
PostMessage(MyhWnd, CWM_SOME_ERROR, 0, 0); //send the_exception or the_exception.error_string() here
}
我希望在对话框中接收消息并显示the_exception.error_string()
LPARAM CMyDlg::SomeError(WPARAM, LPARAM)
{
show_error( ?????
return 0;
}
我想使用PostMessage传递std::string the_exception.error_string()
也可以。
推荐答案
您不能在PostMessage中传递字符串的地址,因为该字符串在堆栈上可能是线程本地的。当另一个线程拾起它时,它可能已被销毁。
相反,您应该通过new创建一个新的字符串或异常对象,并将其地址传递给另一个线程(通过PostMessage中的WPARAM或LPARAM参数)。然后,另一个线程拥有该对象并负责销毁它。
以下是一些示例代码,说明了如何实现这一点:
try
{
// do stuff
}
catch (const MyException& the_exception)
{
PostMessage(myhWnd, CWM_SOME_ERROR, 0, new std::string(the_exception.error_string));
}
LPARAM CMyDlg::SomeError(WPARAM, LPARAM lParam)
{
// Wrap in a unique_ptr so it is automatically destroyed.
std::unique_ptr<std::string> msg = reinterpret_cast<std::string*>(lParam);
// Do stuff with message
return 0;
}
这篇关于如何通过PostMessage发送字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何通过PostMessage发送字符串?


猜你喜欢
- 将 hdc 内容复制到位图 2022-09-04
- 如何提取 __VA_ARGS__? 2022-01-01
- GDB 不显示函数名 2022-01-01
- 将函数的返回值分配给引用 C++? 2022-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- XML Schema 到 C++ 类 2022-01-01
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- DoEvents 等效于 C++? 2021-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01