如何通过PostMessage发送字符串? [英] How to send a string via PostMessage?

查看:71
本文介绍了如何通过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发送字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆