代码之家  ›  专栏  ›  技术社区  ›  LLucasAlday

如何通过PostMessage发送字符串?

  •  17
  • LLucasAlday  · 技术社区  · 16 年前

    在我的应用程序中,我想从不同的线程向对话框发送消息。

    大致如下:

    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;
    }
    

    std::string the_exception.error_string()

    3 回复  |  直到 11 年前
        1
  •  13
  •   Michael    16 年前

    您无法在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;
    }
    
        2
  •  1
  •   Remus Rusanu    16 年前

    synchronous

    调用线程、窗口 子程序。如果指定的窗口 是由另一个线程创建的 调用相应的窗口 接收线程执行消息 阻塞,直到接收线程 处理消息

        3
  •  0
  •   Alan    16 年前

    CMyDlg )在发布消息后,您仍然可以将错误字符串存储在成员变量中,并在消息处理程序中从中读取。

    推荐文章