Friday, January 12, 2007

A small note about UI threads.

What is a UI thread ?? its a normal thread with a windows. thats all . But the danger comes when you are creating MFC window's objects like CFrameWnd inside a normal thread created using CreateThread API function.

For example..
CreateThread(0,0,ThreadProc);


 WINAPI ThreadProc()
{


    CFrameWnd * p  = new CFrameWnd()'
    p->Create(0,"booommm");
    p->ShowWindow(1); // normal show..


    while(GetMessage())
   {
         TranslalteMsg(); DispatchMsg();
   }
    return 1;
}

 When this code executes it will crash.. so use normal CreateWindow() function instead of CFrameWnd :: Create()..

If you want to use CFrameWnd use class CWinThread or AfxBeginThread() for creating threads.. Following code shows how it can be done with CWinThread class..

class myThread: public CWinThread
{


 public  :
    BOOL InitInstance()
    {
         CFrameWnd *ptr = new CFrameWnd();
         pt->Create("0","painter man");
         pt->ShowWindow(1);
     }
}

one more thing is you won't need to write a messge loop for this window. This will be autmatically done by this class in CWinThread::Run()..
Life is more easy... 



No comments: