1、创建和l止U程 在MFCE序中创Z个线E,宜调用AfxBeginThread函数。该函数因参C同而具有两U重载版本,分别对应工作者线E和用户接口QUIQ线E?br /> 工作者线E?br /> CWinThread *AfxBeginThread( AFX_THREADPROC pfnThreadProc, //控制函数 LPVOID pParam, //传递给控制函数的参?br /> int nPriority = THREAD_PRIORITY_NORMAL, //U程的优先 UINT nStackSize = 0, //U程的堆栈大?br /> DWORD dwCreateFlags = 0, //U程的创建标?br /> LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL //U程的安全属?br />); |
工作者线E编E较为简单,只需~写U程控制函数和启动线E即可。下面的代码l出了定义一个控制函数和启动它的q程Q?br /> //U程控制函数 UINT MfcThreadProc(LPVOID lpParam) { CExampleClass *lpObject = (CExampleClass*)lpParam; if (lpObject == NULL || !lpObject->IsKindof(RUNTIME_CLASS(CExampleClass))) return - 1; //输入参数非法 //U程成功启动 while (1) { ...// } return 0; }
//在MFCE序中启动线E?br />AfxBeginThread(MfcThreadProc, lpObject); |
UIU程 创徏用户界面U程Ӟ必须首先从CWinThread zc,q?DECLARE_DYNCREATE ?IMPLEMENT_DYNCREATE 宏声明此cR?br /> 下面l出了CWinThreadcȝ原型Q添加了关于光要函数功能和是否需要被l承c重载的注释Q: class CWinThread : public CCmdTarget { DECLARE_DYNAMIC(CWinThread)
public: // Constructors CWinThread(); BOOL CreateThread(DWORD dwCreateFlags = 0, UINT nStackSize = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL);
// Attributes CWnd* m_pMainWnd; // main window (usually same AfxGetApp()->m_pMainWnd) CWnd* m_pActiveWnd; // active main window (may not be m_pMainWnd) BOOL m_bAutoDelete; // enables 'delete this' after thread termination
// only valid while running HANDLE m_hThread; // this thread's HANDLE operator HANDLE() const; DWORD m_nThreadID; // this thread's ID
int GetThreadPriority(); BOOL SetThreadPriority(int nPriority);
// Operations DWORD SuspendThread(); DWORD ResumeThread(); BOOL PostThreadMessage(UINT message, WPARAM wParam, LPARAM lParam);
// Overridables //执行U程实例初始化,必须重写 virtual BOOL InitInstance();
// running and idle processing //控制U程的函敎ͼ包含消息泵,一般不重写 virtual int Run();
//消息调度到TranslateMessage和DispatchMessage之前对其q行{选, //通常不重?br /> virtual BOOL PreTranslateMessage(MSG* pMsg);
virtual BOOL PumpMessage(); // low level message pump
//执行U程特定的闲|时间处理,通常不重?br /> virtual BOOL OnIdle(LONG lCount); // return TRUE if more idle processing virtual BOOL IsIdleMessage(MSG* pMsg); // checks for special messages
//U程l止时执行清除,通常需要重?br /> virtual int ExitInstance(); // default will 'delete this'
//截获qE的消息和命令处理程序引发的未处理异常,通常不重?br /> virtual LRESULT ProcessWndProcException(CException* e, const MSG* pMsg);
// Advanced: handling messages sent to message filter hook virtual BOOL ProcessMessageFilter(int code, LPMSG lpMsg);
// Advanced: virtual access to m_pMainWnd virtual CWnd* GetMainWnd();
// Implementation public: virtual ~CWinThread(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; int m_nDisablePumpCount; // Diagnostic trap to detect illegal re-entrancy #endif void CommonConstruct(); virtual void Delete(); // 'delete this' only if m_bAutoDelete == TRUE
// message pump for Run MSG m_msgCur; // current message
public: // constructor used by implementation of AfxBeginThread CWinThread(AFX_THREADPROC pfnThreadProc, LPVOID pParam);
// valid after construction LPVOID m_pThreadParams; // generic parameters passed to starting function AFX_THREADPROC m_pfnThreadProc;
// set after OLE is initialized void (AFXAPI* m_lpfnOleTermOrFreeLib)(BOOL, BOOL); COleMessageFilter* m_pMessageFilter;
protected: CPoint m_ptCursorLast; // last mouse position UINT m_nMsgLast; // last mouse message BOOL DispatchThreadMessageEx(MSG* msg); // helper void DispatchThreadMessage(MSG* msg); // obsolete };
|
启动UIU程的AfxBeginThread函数的原型ؓQ?br /> CWinThread *AfxBeginThread( //从CWinThreadz的类?RUNTIME_CLASS CRuntimeClass *pThreadClass, int nPriority = THREAD_PRIORITY_NORMAL, UINT nStackSize = 0, DWORD dwCreateFlags = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL ); |
我们可以方便C用VC++ 6.0cd导定义一个承自CWinThread的用LE类。下面给Z生我们自定义的CWinThread子类CMyUIThread的方法?br /> 打开VC++ 6.0cd|在如下窗口中选择Base ClasscMؓCWinThreadQ输入子cd为CMyUIThreadQ点?OK"按钮后就产生了类CMyUIThread?br /> 其源代码框架为: ///////////////////////////////////////////////////////////////////////////// // CMyUIThread thread
class CMyUIThread : public CWinThread { DECLARE_DYNCREATE(CMyUIThread) protected: CMyUIThread(); // protected constructor used by dynamic creation
// Attributes public:
// Operations public:
// Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CMyUIThread) public: virtual BOOL InitInstance(); virtual int ExitInstance(); //}}AFX_VIRTUAL
// Implementation protected: virtual ~CMyUIThread();
// Generated message map functions //{{AFX_MSG(CMyUIThread) // NOTE - the ClassWizard will add and remove member functions here. //}}AFX_MSG
DECLARE_MESSAGE_MAP() };
///////////////////////////////////////////////////////////////////////////// // CMyUIThread
IMPLEMENT_DYNCREATE(CMyUIThread, CWinThread)
CMyUIThread::CMyUIThread() {}
CMyUIThread::~CMyUIThread() {}
BOOL CMyUIThread::InitInstance() { // TODO: perform and per-thread initialization here return TRUE; }
int CMyUIThread::ExitInstance() { // TODO: perform any per-thread cleanup here return CWinThread::ExitInstance(); }
BEGIN_MESSAGE_MAP(CMyUIThread, CWinThread) //{{AFX_MSG_MAP(CMyUIThread) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_MSG_MAP END_MESSAGE_MAP() |
使用下列代码可以启动这个UIU程Q?br /> CMyUIThread *pThread; pThread = (CMyUIThread*) AfxBeginThread( RUNTIME_CLASS(CMyUIThread) ); |
另外Q我们也可以不用AfxBeginThread 创徏U程Q而是分如下两步完成: Q?Q调用线E类的构造函数创Z个线E对象; Q?Q调用CWinThread::CreateThread函数来启动该U程?br /> 在线E自w内调用AfxEndThread函数可以l止该线E: void AfxEndThread( UINT nExitCode //the exit code of the thread ); |
对于UIU程而言Q如果消息队列中攑օ了WM_QUIT消息Q将l束U程?br /> 关于UIU程和工作者线E的分配Q最好的做法是:所有与UI相关的操作放入主U程Q其它的Ua的运工作交l独立的C工作者线E?br /> 候捷先生早些旉喜欢为MDIE序的每个窗口创Z个线E,他后来澄清了q个错误。因为如果ؓMDIE序的每个窗口都单独创徏一个线E,在窗口进行切换的时候,进行线E的上下文切换!
2.U程间通信 MFC中定义了l承自CSyncObjectcȝCCriticalSection
、CCEvent、CMutex、CSemaphorecd装和化了WIN32
API所提供的界区、事件、互斥和信号量。用这些同步机Ӟ必须包含"Afxmt.h"头文件。下囄Zcȝl承关系Q?br /> 作ؓCSyncObjectcȝl承c,我们仅仅使用基类CSyncObject的接口函数就可以方便、统一的操作CCriticalSection 、CCEvent、CMutex、CSemaphorec,下面是CSyncObjectcȝ原型Q?br /> class CSyncObject : public CObject { DECLARE_DYNAMIC(CSyncObject)
// Constructor public: CSyncObject(LPCTSTR pstrName);
// Attributes public: operator HANDLE() const; HANDLE m_hObject;
// Operations virtual BOOL Lock(DWORD dwTimeout = INFINITE); virtual BOOL Unlock() = 0; virtual BOOL Unlock(LONG /* lCount */, LPLONG /* lpPrevCount=NULL */) { return TRUE; }
// Implementation public: virtual ~CSyncObject(); #ifdef _DEBUG CString m_strName; virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif friend class CSingleLock; friend class CMultiLock; }; |
CSyncObjectcL主要的两个函数是Lock和UnlockQ若我们直接使用CSyncObjectcd其派生类Q我们需要非常小心地在Lock之后调用Unlock?br /> MFC提供的另两个cCSingleLockQ等待一个对象)和CMultiLockQ等待多个对象)为我们编写应用程序提供了更灵zȝ机制Q下面以实际来阐qCSingleLock的用法: class CThreadSafeWnd { public: CThreadSafeWnd(){} ~CThreadSafeWnd(){} void SetWindow(CWnd *pwnd) { m_pCWnd = pwnd; } void PaintBall(COLORREF color, CRect &rc); private: CWnd *m_pCWnd; CCriticalSection m_CSect; };
void CThreadSafeWnd::PaintBall(COLORREF color, CRect &rc) { CSingleLock csl(&m_CSect); //~省的Timeout是INFINITEQ只有m_Csect被激z,csl.Lock()才能q回 //trueQ这里一直等?br /> if (csl.Lock()) ; { // not necessary //AFX_MANAGE_STATE(AfxGetStaticModuleState( )); CDC *pdc = m_pCWnd->GetDC(); CBrush brush(color); CBrush *oldbrush = pdc->SelectObject(&brush); pdc->Ellipse(rc); pdc->SelectObject(oldbrush); GdiFlush(); // don't wait to update the display } } |
上述实例讲述了用CSingleLock对Windows GDI相关对象q行保护的方法,下面再给Z个其他方面的例子Q?br /> int array1[10], array2[10]; CMutexSection section; //创徏一个CMutexcȝ对象
//赋值线E控制函?br />UINT EvaluateThread(LPVOID param) { CSingleLock singlelock; singlelock(§ion);
//互斥区域 singlelock.Lock(); for (int i = 0; i < 10; i++) array1[i] = i; singlelock.Unlock(); } //拯U程控制函数 UINT CopyThread(LPVOID param) { CSingleLock singlelock; singlelock(§ion);
//互斥区域 singlelock.Lock(); for (int i = 0; i < 10; i++) array2[i] = array1[i]; singlelock.Unlock(); } }
AfxBeginThread(EvaluateThread, NULL); //启动赋值线E?br />AfxBeginThread(CopyThread, NULL); //启动拯U程 |
上面的例子中启动了两个线EEvaluateThread和CopyThreadQ线EEvaluateThread?0个数赋值给数组array1
[]Q线ECopyThread数larray1[]拯l数larray2[]。由于数l的拯和赋值都是整体行为,如果不以互斥形式执行代码D: for (int i = 0; i < 10; i++) array1[i] = i; |
?br /> for (int i = 0; i < 10; i++) array2[i] = array1[i]; |
其结果是很难预料的! 除了可用CCriticalSection、CEvent、CMutex、CSemaphore作ؓU程间同步通信的方式以外,我们q可以利用PostThreadMessage函数在线E间发送消息: BOOL PostThreadMessage(DWORD idThread, // thread identifier UINT Msg, // message to post WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ); |
3.U程与消息队?br /> 在WIN32中,每一个线E都对应着一个消息队列。由于一个线E可以生数个窗口,所以ƈ不是每个H口都对应着一个消息队列。下列几句话应该作ؓ"定理"被记住: "定理" 一 所有生给某个H口的消息,都先由创个窗口的U程处理Q?br /> "定理" ?br /> Windows屏幕上的每一个控仉是一个窗口,有对应的H口函数?br /> 消息的发送通常有两U方式,一是SendMessageQ一是PostMessageQ其原型分别为: LRESULT SendMessage(HWND hWnd, // handle of destination window UINT Msg, // message to send WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ); BOOL PostMessage(HWND hWnd, // handle of destination window UINT Msg, // message to post WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ); |
两个函数原型中的四个参数的意义相同,但是SendMessage和PostMessage的行为有差异。SendMessage必须{待消息被处理后
才返回,而PostMessage仅仅消息放入消息队列。SendMessage的目标窗口如果属于另一个线E,则会发生U程上下文切换,{待另一U程
处理完成消息。ؓ了防止另一U程当掉Q导致SendMessage永远不能q回Q我们可以调用SendMessageTimeout函数Q?br /> LRESULT SendMessageTimeout( HWND hWnd, // handle of destination window UINT Msg, // message to send WPARAM wParam, // first message parameter LPARAM lParam, // second message parameter UINT fuFlags, // how to send the message UINT uTimeout, // time-out duration LPDWORD lpdwResult // return value for synchronous call ); |
4. MFCU程、消息队列与MFCE序?生死因果" 分析MFCE序的主U程启动及消息队列处理的q程有助于我们q一步理解UIU程与消息队列的关系Qؓ此我们需要简单地叙述一下MFCE序?生死因果"Q侯P《深入浅出MFC》)?br /> 使用VC++ 6.0的向导完成一个最单的单文架构MFC应用E序MFCThreadQ?br /> Q?Q?输入MFC EXE工程名MFCThreadQ?br /> Q?Q?选择单文档架构,不支持Document/Viewl构Q?br /> Q?Q?ActiveX?D container{其他选项都选择无?br /> 我们来分析这个工E。下面是产生的核心源代码Q?br /> MFCThread.h 文g class CMFCThreadApp : public CWinApp { public: CMFCThreadApp();
// Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CMFCThreadApp) public: virtual BOOL InitInstance(); //}}AFX_VIRTUAL
// Implementation
public: //{{AFX_MSG(CMFCThreadApp) afx_msg void OnAppAbout(); // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; |
MFCThread.cpp文g CMFCThreadApp theApp;
///////////////////////////////////////////////////////////////////////////// // CMFCThreadApp initialization
BOOL CMFCThreadApp::InitInstance() { ?br /> CMainFrame* pFrame = new CMainFrame; m_pMainWnd = pFrame;
// create and load the frame with its resources pFrame->LoadFrame(IDR_MAINFRAME,WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, NULL,NULL); // The one and only window has been initialized, so show and update it. pFrame->ShowWindow(SW_SHOW); pFrame->UpdateWindow();
return TRUE; } |
MainFrm.h文g #include "ChildView.h"
class CMainFrame : public CFrameWnd { public: CMainFrame(); protected: DECLARE_DYNAMIC(CMainFrame)
// Attributes public:
// Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CMainFrame) virtual BOOL PreCreateWindow(CREATESTRUCT& cs); virtual BOOL OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo); //}}AFX_VIRTUAL
// Implementation public: virtual ~CMainFrame(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif CChildView m_wndView;
// Generated message map functions protected: //{{AFX_MSG(CMainFrame) afx_msg void OnSetFocus(CWnd *pOldWnd); // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; |
MainFrm.cpp文g IMPLEMENT_DYNAMIC(CMainFrame, CFrameWnd)
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) //{{AFX_MSG_MAP(CMainFrame) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code ! ON_WM_SETFOCUS() //}}AFX_MSG_MAP END_MESSAGE_MAP()
///////////////////////////////////////////////////////////////////////////// // CMainFrame construction/destruction
CMainFrame::CMainFrame() { // TODO: add member initialization code here }
CMainFrame::~CMainFrame() {}
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if( !CFrameWnd::PreCreateWindow(cs) ) return FALSE; // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs
cs.dwExStyle &= ~WS_EX_CLIENTEDGE; cs.lpszClass = AfxRegisterWndClass(0); return TRUE; } |
ChildView.h文g // CChildView window
class CChildView : public CWnd { // Construction public: CChildView();
// Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CChildView) protected: virtual BOOL PreCreateWindow(CREATESTRUCT& cs); //}}AFX_VIRTUAL
// Implementation public: virtual ~CChildView();
// Generated message map functions protected: //{{AFX_MSG(CChildView) afx_msg void OnPaint(); //}}AFX_MSG DECLARE_MESSAGE_MAP() };
ChildView.cpp文g // CChildView
CChildView::CChildView() {}
CChildView::~CChildView() {}
BEGIN_MESSAGE_MAP(CChildView,CWnd ) //{{AFX_MSG_MAP(CChildView) ON_WM_PAINT() //}}AFX_MSG_MAP END_MESSAGE_MAP()
///////////////////////////////////////////////////////////////////////////// // CChildView message handlers
BOOL CChildView::PreCreateWindow(CREATESTRUCT& cs) { if (!CWnd::PreCreateWindow(cs)) return FALSE;
cs.dwExStyle |= WS_EX_CLIENTEDGE; cs.style &= ~WS_BORDER; cs.lpszClass = AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS,::LoadCursor(NULL, IDC_ARROW), HBRUSH(COLOR_WINDOW+1),NULL);
return TRUE; }
void CChildView::OnPaint() { CPaintDC dc(this); // device context for painting
// TODO: Add your message handler code here // Do not call CWnd::OnPaint() for painting messages } |
文gMFCThread.h和MFCThread.cpp定义和实现的cCMFCThreadAppl承自CWinAppc,而CWinAppcdl承
自CWinThreadc(CWinThreadcdl承自CCmdTargetc)Q所以CMFCThread本质上是一个MFCU程c,下图l出了相
关的cdơ结构:
我们提取CWinAppcd型的一部分Q?br /> class CWinApp : public CWinThread { DECLARE_DYNAMIC(CWinApp) public: // Constructor CWinApp(LPCTSTR lpszAppName = NULL);// default app name // Attributes // Startup args (do not change) HINSTANCE m_hInstance; HINSTANCE m_hPrevInstance; LPTSTR m_lpCmdLine; int m_nCmdShow; // Running args (can be changed in InitInstance) LPCTSTR m_pszAppName; // human readable name LPCTSTR m_pszExeName; // executable name (no spaces) LPCTSTR m_pszHelpFilePath; // default based on module path LPCTSTR m_pszProfileName; // default based on app name
// Overridables virtual BOOL InitApplication(); virtual BOOL InitInstance(); virtual int ExitInstance(); // return app exit code virtual int Run(); virtual BOOL OnIdle(LONG lCount); // return TRUE if more idle processing virtual LRESULT ProcessWndProcException(CException* e,const MSG* pMsg);
public: virtual ~CWinApp(); protected: DECLARE_MESSAGE_MAP() }; |
SDKE序的WinMain 所完成的工作现在由CWinApp 的三个函数完成: virtual BOOL InitApplication(); virtual BOOL InitInstance(); virtual int Run(); |
"CMFCThreadApp theApp;"语句定义的全局变量theApp是整个程式的application objectQ每一个MFC
应用E序都有一个。当我们执行MFCThreadE序的时候,q个全局变量被构造。theApp
配置完成后,WinMain开始执行。但是程序中q没有WinMain的代码,它在哪里呢?原来MFC早已准备好ƈ由Linker直接加到应用E序代码?
的,其原型ؓQ存在于VC++6.0安装目录下提供的APPMODUL.CPP文g中)Q?br /> extern "C" int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { // call shared/exported WinMain return AfxWinMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow); } |
其中调用的AfxWinMain如下Q存在于VC++6.0安装目录下提供的WINMAIN.CPP文g中)Q?br /> int AFXAPI AfxWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { ASSERT(hPrevInstance == NULL);
int nReturnCode = -1; CWinThread* pThread = AfxGetThread(); CWinApp* pApp = AfxGetApp();
// AFX internal initialization if (!AfxWinInit(hInstance, hPrevInstance, lpCmdLine, nCmdShow)) goto InitFailure;
// App global initializations (rare) if (pApp != NULL && !pApp->InitApplication()) goto InitFailure;
// Perform specific initializations if (!pThread->InitInstance()) { if (pThread->m_pMainWnd != NULL) { TRACE0("Warning: Destroying non-NULL m_pMainWnd\n"); pThread->m_pMainWnd->DestroyWindow(); } nReturnCode = pThread->ExitInstance(); goto InitFailure; } nReturnCode = pThread->Run();
InitFailure: #ifdef _DEBUG // Check for missing AfxLockTempMap calls if (AfxGetModuleThreadState()->m_nTempMapLock != 0) { TRACE1("Warning: Temp map lock count non-zero (%ld).\n", AfxGetModuleThreadState()->m_nTempMapLock); } AfxLockTempMaps(); AfxUnlockTempMaps(-1); #endif
AfxWinTerm(); return nReturnCode; } |
我们提取dQ实际上Q这个函数做的事情主要是Q?br /> CWinThread* pThread = AfxGetThread(); CWinApp* pApp = AfxGetApp(); AfxWinInit(hInstance, hPrevInstance, lpCmdLine, nCmdShow) pApp->InitApplication() pThread->InitInstance() pThread->Run(); |
其中QInitApplication
是注册窗口类别的场所QInitInstance是生窗口ƈ昄H口的场所QRun是提取ƈ分派消息的场所。这PMFC同WIN32
SDKE序对应h了。CWinThread::Run是程序生命的"zL源头"Q侯P《深入浅出MFC》,函数存在于VC++
6.0安装目录下提供的THRDCORE.CPP文g中)Q?br /> // main running routine until thread exits 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 } |
其中的PumpMessage函数又对应于Q?br /> ///////////////////////////////////////////////////////////////////////////// // CWinThread implementation helpers
BOOL CWinThread::PumpMessage() { ASSERT_VALID(this);
if (!::GetMessage(&m_msgCur, NULL, NULL, NULL)) { return FALSE; }
// process this message if(m_msgCur.message != WM_KICKIDLE && !PreTranslateMessage(&m_msgCur)) { ::TranslateMessage(&m_msgCur); ::DispatchMessage(&m_msgCur); } return TRUE; } |
因此Q忽略IDLE状态,整个RUN的执行提取主q就是: do { ::GetMessage(&msg,...); PreTranslateMessage{&msg); ::TranslateMessage(&msg); ::DispatchMessage(&msg); ... } while (::PeekMessage(...)); |
由此Q我们徏立了MFC消息获取和派生机制与WIN32 SDKE序之间的对应关pR下面l分析MFC消息?l行"q程?br />
在MFC中,只要是CWnd 衍生cdQ就可以拦下MWindows消息。与H口无关的MFCcdQ例如CDocument
和CWinAppQ如果也惛_理消息,必须衍生自CCmdTargetQƈ且只可能收到WM_COMMAND消息。所有能q行MESSAGE_MAP的类
都承自CCmdTargetQ如Q?br /> MFC中MESSAGE_MAP的定义依赖于以下三个宏: DECLARE_MESSAGE_MAP()
BEGIN_MESSAGE_MAP( theClass, //Specifies the name of the class whose message map this is baseClass //Specifies the name of the base class of theClass )
END_MESSAGE_MAP() |
我们E序中涉及到的有QMFCThread.h、MainFrm.h、ChildView.h文g DECLARE_MESSAGE_MAP() MFCThread.cpp文g BEGIN_MESSAGE_MAP(CMFCThreadApp, CWinApp) //{{AFX_MSG_MAP(CMFCThreadApp) ON_COMMAND(ID_APP_ABOUT, OnAppAbout) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP END_MESSAGE_MAP() MainFrm.cpp文g BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) //{{AFX_MSG_MAP(CMainFrame) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code ! ON_WM_SETFOCUS() //}}AFX_MSG_MAP END_MESSAGE_MAP() ChildView.cpp文g BEGIN_MESSAGE_MAP(CChildView,CWnd ) //{{AFX_MSG_MAP(CChildView) ON_WM_PAINT() //}}AFX_MSG_MAP END_MESSAGE_MAP() |
p些宏QMFC建立了一个消息映表Q消息流动网Q,按照消息动|匹配对应的消息处理函数Q完成整个消息的"l行"?br /> 看到q里怿你有q样的疑问:E序定义了CWinAppcȝtheApp全局变量Q可是从来没有调用AfxBeginThread或theApp.CreateThread启动U程呀QtheApp对应的线E是怎么启动的? {:MFC在这里用了很高明的一招。实际上Q程序开始运行,W一个线E是由操作系l(OSQ启动的Q在CWinApp的构造函数里QMFCtheApp"对应"向了q个U程Q具体的实现是这LQ?br /> CWinApp::CWinApp(LPCTSTR lpszAppName) { if (lpszAppName != NULL) m_pszAppName = _tcsdup(lpszAppName); else m_pszAppName = NULL;
// initialize CWinThread state AFX_MODULE_STATE *pModuleState = _AFX_CMDTARGET_GETSTATE(); AFX_MODULE_THREAD_STATE *pThreadState = pModuleState->m_thread; ASSERT(AfxGetThread() == NULL); pThreadState->m_pCurrentWinThread = this; ASSERT(AfxGetThread() == this); m_hThread = ::GetCurrentThread(); m_nThreadID = ::GetCurrentThreadId();
// initialize CWinApp state ASSERT(afxCurrentWinApp == NULL); // only one CWinApp object please pModuleState->m_pCurrentWinApp = this; ASSERT(AfxGetApp() == this);
// in non-running state until WinMain m_hInstance = NULL; m_pszHelpFilePath = NULL; m_pszProfileName = NULL; m_pszRegistryKey = NULL; m_pszExeName = NULL; m_pRecentFileList = NULL; m_pDocManager = NULL; m_atomApp = m_atomSystemTopic = NULL; //微Y懒鬼Q或者他认ؓ //q样q等含义更明? m_lpCmdLine = NULL; m_pCmdInfo = NULL;
// initialize wait cursor state m_nWaitCursorCount = 0; m_hcurWaitCursorRestore = NULL;
// initialize current printer state m_hDevMode = NULL; m_hDevNames = NULL; m_nNumPreviewPages = 0; // not specified (defaults to 1)
// initialize DAO state m_lpfnDaoTerm = NULL; // will be set if AfxDaoInit called
// other initialization m_bHelpMode = FALSE; m_nSafetyPoolSize = 512; // default size } |
很显ӞtheApp成员变量都被赋予OS启动的这个当前线E相关的|如代码: m_hThread = ::GetCurrentThread();//theApp的线E句柄等于当前线E句? m_nThreadID = ::GetCurrentThreadId();//theApp的线EID{于当前U程ID |
所以CWinAppcd乎只是ؓMFCE序的第一个线E量w定制的Q它不需要也不能被AfxBeginThread?
theApp.CreateThread"再次"启动。这是CWinAppcdtheApp全局变量的内涵!如果你要再增加一个UIU程Q不要承类
CWinAppQ而应l承cCWinThread。而参考第1节,׃我们一般以ȝE(在MFCE序里实际上是OS启动的第一个线E)处理所有窗口的
消息Q所以我们几乎没有再启动UIU程的需求!
|