开发者

How to access AfxGetMainWnd() from CWinThread?

I'm trying to create a worker thread in a class called ClientManager, but I can't get access to AfxGetMainWnd() from the new CWinThread, i.e:

UINT ClientManager::WorkerThreadProc(开发者_C百科 LPVOID param ){
    ClientManager *pThis = reinterpret_cast<ClientManager*>(param);
    return pThis -> DoThreadJob();
}
UINT ClientManager::DoThreadJob(){
    createClientSession("1");
    return 0;
}

void ClientManager::createThread(){
    m_clientManagerThread = AfxBeginThread(WorkerThreadProc,this,0,0,0,NULL);           
}

void ClientManager::createClientSession(CString clientID){
    if (AfxGetMainWnd()->GetSafeHwnd()== NULL){
        _cprintf("NULL");
    }
}

Output: NULL

AfxGetMainWnd()->GetSafeHwnd() works in the main thread.

Thanks!


AfxGetApp()->GetMainWnd() works in threads.

No need to store the window handle in a member of ClientManager.


The documentation says:

If AfxGetMainWnd is called from the application's primary thread, it returns the application's main window according to the above rules. If the function is called from a secondary thread in the application, the function returns the main window associated with the thread that made the call.

So you need to make the call from the main thread. Do this just before you call AfxBeginThread and store the resulting window handle in a member of ClientManager. Then your thread can gain access to the window handle via its ClientManager reference.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜