如何在多线程函数MFC中获取对话框类的指针 [英] How to take a pointer of dialog class in a multithread function MFC

查看:519
本文介绍了如何在多线程函数MFC中获取对话框类的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在多线程函数中访问我的对话框UI(编辑框),该函数定义了全局或独立函数. CSampleDlg* m_dlg=(CSampleDlg*)_param;这里是_param是线程函数的参数.当我尝试它崩溃在这里:ASSERT(::IsWindow(m_hWnd));

//这是示例代码MFC

UINT MessageThread(LPVOID _param)
{
    CServerDlg* m_dlg=(CServerDlg*)_param; 
    char cChar[1024];
    CString strmsg=L"";

    while (!stopNow && (currValue < maxValue))
    {
        m_dlg->m_messagebox.GetWindowTextW(strmsg); //m_messagebox :editbox
        sprintf(cChar,"%s",CW2A(strmsg));
        char *buff=(char*)&cChar;
        m_dlg->m_server.Send(buff,sizeof(cChar));
        currValue++;
        Sleep(50);  
    }

    return TRUE;
}

解决方案

如果要访问其后面的窗口对象,则跨线程使用CWnd指针很危险. CWnd指针存储在每个线程映射中.使用由MFC包装的window API函数可能会失败或引发ASSERT.

您可以使用嵌入式m_hWnd句柄,并且可以将GetWindowText与该句柄一起使用.但这并不是一个很好的解决方案.

UI和其他workerthread操作应严格分开.因此,与直接访问窗口相比,更好的方法是通过任何其他方法将要发送的信息发送给workerthread.

i want to access my dialog box UI(edit box) in a multithread function which is i define global or independent function. CSampleDlg* m_dlg=(CSampleDlg*)_param; here is _param is a parameter of thread function. when i tried this its crashing here : ASSERT(::IsWindow(m_hWnd));

//here is sample code mfc

UINT MessageThread(LPVOID _param)
{
    CServerDlg* m_dlg=(CServerDlg*)_param; 
    char cChar[1024];
    CString strmsg=L"";

    while (!stopNow && (currValue < maxValue))
    {
        m_dlg->m_messagebox.GetWindowTextW(strmsg); //m_messagebox :editbox
        sprintf(cChar,"%s",CW2A(strmsg));
        char *buff=(char*)&cChar;
        m_dlg->m_server.Send(buff,sizeof(cChar));
        currValue++;
        Sleep(50);  
    }

    return TRUE;
}

解决方案

Using CWnd pointers across threads is dangerous, if you want to access the window object behind it. CWnd pointers are stored in a per thread map. Using a window API function that is wrapped by the MFC may fail or throw an ASSERT.

You may use the embedded m_hWnd handle and you may use GetWindowText with this handle. But even isn't really a good solution.

UI and other workerthread actions should be strictly splitted. So better is to send the information you want to send to the workerthread y any other method than directly accessing the window.

这篇关于如何在多线程函数MFC中获取对话框类的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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