1.创建线程类。从CWinThread派生CTestThread类。CTestThread();上面的protected:改成public:。为了简单起见,在重载的InitInstance()函数里,创建一个简单的CFrameWnd类,并显示其窗口。 // CTestThread
class CTestThread : public CWinThread
{
DECLARE_DYNCREATE(CTestThread)
//protected:
public:
CTestThread();
virtual ~CTestThread();
public:
virtual BOOL InitInstance();
virtual int ExitInstance();
protected:
DECLARE_MESSAGE_MAP()
};
// CTestThread
IMPLEMENT_DYNCREATE(CTestThread, CWinThread)
CTestThread::CTestThread()
{
}
CTestThread::~CTestThread()
{
}
BOOL CTestThread::InitInstance()
{
CFrameWnd* pWnd = new CFrameWnd;
pWnd->Create(NULL,L"CWinThread Test");
pWnd->ShowWindow(SW_SHOW);
pWnd->UpdateWindow();
m_pMainWnd = pWnd;
return TRUE;
}
int CTestThread::ExitInstance()
{
// TODO: perform. any per-thread cleanup here
return CWinThread::ExitInstance();
}
BEGIN_MESSAGE_MAP(CTestThread, CWinThread)
END_MESSAGE_MAP() 2.起动线程。 void Test()
{
CRuntimeClass *pRuntime = RUNTIME_CLASS(CTestThread);
g_pThread = (CTestThread*)pRuntime->CreateObject();
g_pThread->CreateThread(0, 0, NULL);
...
} 3.停止,删除线程。如果CWinThread的构造函数中的m_bAutoDelete成员被设成TRUE,窗口关闭时,Delete()函数会被自动调用。不然的话,自己进行删除处理。 可以重载SuspendThread(),Run()等函数来实现特有的处理。 |
|