在Visual C++ 6.0編程環境中,我們既可以編寫C風格的32位Win32應用程序,也可以利用MFC類庫編寫C++風格的應用程序,二者各有其優缺點。基于Win32的應用程序執行代碼小巧,運行效率高,但要求程序員編寫的代碼較多,且需要管理系統提供給程序的所有資源;而基于MFC類庫的應用程序可以快速建立起應用程序,類庫為程序員提供了大量的封裝類,而且Developer Studio為程序員提供了一些工具來管理用戶源程序,其缺點是類庫代碼很龐大。由于使用類庫所帶來的快速、簡捷和功能強大等優越性,因此除非有特殊的需要,否則Visual C++推薦使用MFC類庫進行程序開發。
void CMultiThread5Dlg::OnStart() {// TODO: Add your control notification handler code hereUpdateData(TRUE);Info.nMilliSecond=m_nMilliSecond;Info.pctrlProgress=&m_ctrlProgress;pThread=AfxBeginThread(ThreadFunc,&Info);} 在函數BOOL CMultiThread3Dlg::OnInitDialog()中添加語句: {……// TODO: Add extra initialization herem_ctrlProgress.SetRange(0,99);m_nMilliSecond=10;UpdateData(FALSE);return TRUE; // return TRUE unless you set the focus to a control} 添加線程處理函數: UINT ThreadFunc(LPVOID lpParam){threadInfo* pInfo=(threadInfo*)lpParam;for(int i=0;i<100;i++){int nTemp=pInfo->nMilliSecond;pInfo->pctrlProgress->SetPos(i);Sleep(nTemp);}return 0;}
用 MFC 類庫編程實現用戶界面線程
創建用戶界面線程的步驟:
使用ClassWizard創建類CWinThread的派生類(以CUIThread類為例) class CUIThread : public CWinThread{DECLARE_DYNCREATE(CUIThread)protected:CUIThread(); // protected constructor used by dynamic creation// Attributespublic:// Operationspublic:// Overrides// ClassWizard generated virtual function overrides//{{AFX_VIRTUAL(CUIThread)public:virtual BOOL InitInstance();virtual int ExitInstance();//}}AFX_VIRTUAL// Implementationprotected:virtual ~CUIThread();// Generated message map functions//{{AFX_MSG(CUIThread)// NOTE - the ClassWizard will add and remove member functions here.//}}AFX_MSGDECLARE_MESSAGE_MAP()};
為對話框IDD_UITHREADDLG創建一個基于CDialog的類CUIThreadDlg。使用ClassWizard為CUIThreadDlg類添加WM_LBUTTONDOWN消息的處理函數OnLButtonDown,如下: void CUIThreadDlg::OnLButtonDown(UINT nFlags, CPoint point) {AfxMessageBox("You Clicked The Left Button!");CDialog::OnLButtonDown(nFlags, point);}
在UIThread.h中添加 #include "UIThreadDlg.h" 并在CUIThread類中添加protected變量CUIThread m_dlg: class CUIThread : public CWinThread{DECLARE_DYNCREATE(CUIThread)protected:CUIThread(); // protected constructor used by dynamic creation// Attributespublic:// Operationspublic:// Overrides// ClassWizard generated virtual function overrides//{{AFX_VIRTUAL(CUIThread)public:virtual BOOL InitInstance();virtual int ExitInstance();//}}AFX_VIRTUAL// Implementationprotected:CUIThreadDlg m_dlg;virtual ~CUIThread();// Generated message map functions//{{AFX_MSG(CUIThread)// NOTE - the ClassWizard will add and remove member functions here.//}}AFX_MSGDECLARE_MESSAGE_MAP()};