2009. 3. 27. 14:40

UI Thread 생성하기

아래 코드 예는 MFC 를 지웒하는 Win32 프로젝트에서 UI Thread를 생성하고, 이 쓰레드에서 생성한 윈도우에서 왼쪽 마우스를 클릭하면 종료하는 프로그램이다.

 #include "stdafx.h"

#include "Win32Sample.h"

 

#ifdef _DEBUG

#define new DEBUG_NEW

#endif

 

#include <afxmt.h>

 

// The one and only application object

 

CWinApp theApp;

 

 

// The CMainWindow class

class CMainWindow : public CFrameWnd

{

public:

        CMainWindow ();

 

protected:

        afx_msg void OnLButtonDown (UINT, CPoint);

        DECLARE_MESSAGE_MAP ()

};

 

BEGIN_MESSAGE_MAP (CMainWindow, CFrameWnd)

        ON_WM_LBUTTONDOWN ()

END_MESSAGE_MAP ()

 

CMainWindow::CMainWindow ()

{

        Create (NULL, _T ("UI Thread Window"));

}

 

void CMainWindow::OnLButtonDown (UINT nFlags, CPoint point)

{

        PostMessage (WM_QUIT, 0, 0);

}

 

// The CUIThread class

class CUIThread : public CWinThread

{

        DECLARE_DYNCREATE (CUIThread)

 

public:

        virtual BOOL InitInstance ();

        virtual int ExitInstance() {

               delete m_pMainWnd;

               return 0;

        }

};

 

IMPLEMENT_DYNCREATE (CUIThread, CWinThread)

 

BOOL CUIThread::InitInstance ()

{

        m_pMainWnd = new CMainWindow;

        m_pMainWnd->ShowWindow (SW_SHOW);

        m_pMainWnd->UpdateWindow ();

        return TRUE;

}

 

using namespace std;

 

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])

{

        int nRetCode = 0;

 

        // initialize MFC and print and error on failure

        if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))

        {

               // TODO: change error code to suit your needs

               _tprintf(_T("Fatal Error: MFC initialization failed\n"));

               nRetCode = 1;

        }

        else

        {

               // TODO: code your application's behavior here.

 

               CWinThread* pThread = AfxBeginThread (RUNTIME_CLASS (CUIThread), 0, 0, CREATE_SUSPENDED);

               pThread->m_bAutoDelete = FALSE;

               pThread->ResumeThread();

       

               WaitForSingleObject(pThread->m_hThread, INFINITE);  

               delete pThread;

        }

 

        return nRetCode;

}