CWinThread的Run()成员函数是一个虚函数,这就意味着你可以重载它,进行自己的处理。你可以从CWinThread派生一个新类,在新类中重载Run()。

解决方案 »

  1.   

    重载run后,是系统自动执行呢还是我在什么地方执行呢?
    还有我怎样保证线程的生命周期与主线程的一致呢?
      

  2.   

    系统自动执行.你要了解详细情况,请看MFC源码.在主线程的ExitInstance()中调用TerminateThread()就可实线程生命期一致.
      

  3.   

    实现一个用户界面线程(带有消息循环),应重载CWinThread以下的方法:
    ExitInstance,InitInstance,OnIdle,PreTranslateMessage,ProcessWndProcException和Run,其中Run是最重要的啦..,其它再重载ExitInstance和InitInstance就可以了.
    另外还要注意:DECLARE_DYNCREATE和IMPLEMENT_DYNCREATE该类.
    启动线程用AfxBeginThread,
    AfxBeginThread有两个重载的版本,一个用于工作者线程,一个用于界面线程,
    CWinThread* AfxBeginThread( CRuntimeClass* pThreadClass, int nPriority = THREAD_PRIORITY_NORMAL, UINT nStackSize = 0, DWORD dwCreateFlags = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL );
    这个要提供RuntimeClass的是用于界面线程的.RUN方法是系统调用InitInstance后,自动调用的,通常在其中添加消息循环.
    如下:这是MFC CWinThread 的源代码,就是一个无限的消息泵循环,和SDK程序中的
    WinMain的消息循环相同.
    // for tracking the idle time state
    BOOL bIdle = TRUE;
    LONG lIdleCount = 0; // acquire and dispatch messages until a WM_QUIT message is received.
    for (;;)
    {
    // phase1: check to see if we can do idle work
    while (bIdle &&
    !::PeekMessage(&m_msgCur, NULL, NULL, NULL, PM_NOREMOVE))
    {
    // call OnIdle while in bIdle state
    if (!OnIdle(lIdleCount++))
    bIdle = FALSE; // assume "no idle" state
    } // phase2: pump messages while available
    do
    {
    // pump message, but quit on WM_QUIT
    if (!PumpMessage())
    return ExitInstance(); // reset "no idle" state after pumping "normal" message
    if (IsIdleMessage(&m_msgCur))
    {
    bIdle = TRUE;
    lIdleCount = 0;
    } } while (::PeekMessage(&m_msgCur, NULL, NULL, NULL, PM_NOREMOVE));
    }如果你仅仅是想在线程中另起一个窗口而已,很幸运,你只需要重载InitInstance即可.
    在该方法中创建你要的窗口,将其赋值给CWinThread的m_pMainWnd就可以了.这个线程
    将运行该窗口的消息循环,窗口就归这个线程了.