Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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( 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!

like image 703
nbroby Avatar asked Sep 26 '11 08:09

nbroby


2 Answers

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

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

like image 72
Tom Tom Avatar answered Oct 20 '22 00:10

Tom Tom


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.

like image 30
David Heffernan Avatar answered Oct 20 '22 00:10

David Heffernan