MFC通過類、宏進行了層層封裝,搞的神秘兮兮,很容易繞暈。但好在大多數功能都有源代碼,只要耐心看,總可以追溯。
首先,妳的提問中,CWinThread的工作函數不是WinMain,而是Run。其次,如果討論界定在MFC的標準主線程,那麽這是很明確的,同樣是Run函數。
CWinApp是MFC主線程的標準類,派生後的APP類,從InitInstance進入,之後進入了CWinApp類的Run:
int?CWinApp::Run(){
if?(m_pMainWnd?==?NULL?&&?AfxOleGetUserCtrl())
{
//?Not?launched?/Embedding?or?/Automation,?but?has?no?main?window!
TRACE0("Warning:?m_pMainWnd?is?NULL?in?CWinApp::Run?-?quitting?application.\n");
AfxPostQuitMessage(0);
}
return?CWinThread::Run();
}
這裏調用了基類的Run函數,實際就是啟動了主工作函數CWinThread::Run,這個函數的代碼如下:
int?CWinThread::Run(){
ASSERT_VALID(this);
//?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));
}
ASSERT(FALSE);?//?not?reachable
}
在MFC程序中,AfxWinMain實際上只是起到了“承接”的作用,串聯了APP類的幾個函數,並不是真正的工作函數。