2016年6月29日 星期三

MFC AfxBeginThread 使用方法

1.在主要functino的class中使用CWinThread宣告Thread指標。
class CMFCApplication1Dlg : public CDialogEx
{
public:
   CMFCApplication1Dlg(CWnd* pParent = NULL); // 標準建構函式
   CWinThread* pThread;
// 對話方塊資料
#ifdef AFX_DESIGN_TIME
   enum { IDD = IDD_MFCAPPLICATION1_DIALOG };
#endif

   protected:
   virtual void DoDataExchange(CDataExchange* pDX);
   ...
// 程式碼實作
protected:
   ...
}

2.定義MyThread(),必將要執行的工作寫在裡面,可搭配
在 MFC 上使用lusb-win32】一文中提到的Console _cprintf來觀察是否有進入MyThread()。
UINT MyThread(LPVOID LParam)
{
   _cprintf("Start MyThread...\n");
   ...
   while(1){
      _cprintf("Hello World!\n");
   }
   return(0);
}

3.在欲開啟MyThread的Dialog按鈕程式碼中創建Thread
void CMFCApplication1Dlg::OnBnClickedButton1()
{
   pThread = AfxBeginThread(MyThread, NULL);
   ...
}

4.使用TerminateThread關閉MyThread
void CMFCApplication1Dlg::OnBnClickedButton2()
{
   // TODO: 在此加入控制項告知處理常式程式碼
   TerminateThread(pThread->m_hThread, 0);
   _cprintf("Close MyThread............\n");

}


執行結果:
當按下Button1後,會一直執行MyThread()中的「_cprintf("Hello World!\n");」,按下Button2後可以看到確實將MyThread()給關掉,Console不再印出Hello World!!字串。

沒有留言:

張貼留言