Bootstrap

C++ MFC 中使用多线程操作实例



多线程实例(一)

此实例为简单的多线程,实现动态显示时间

1、.h中:

protected:
 HICON m_hIcon;
 HANDLE hThread;//线程句柄
 DWORD threadID;//线程Id
 // Generated message map functions
 //{ {AFX_MSG(CMthread1Dlg)
 virtual BOOL OnInitDialog();
 afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
 afx_msg void OnPaint();
 afx_msg HCURSOR OnQueryDragIcon();
 afx_msg void OnStart();
 afx_msg void OnStop();

2、.cpp中:

volatile BOOL m_bRun;//代表线程是否正常运行

void ThreadProc()
{
 CTime time;
 CString strTime;
 m_bRun = TRUE;

 while(m_bRun)
 {
  time = CTime::GetCurrentTime();
  strTime = time.Format("%H:%M:%S");

  ::SetDlgItemText(AfxGetMainWnd()->m_hWnd,IDC_TIME,strTime);
  Sleep(1000);
 }
}
class CAboutDlg : public CDialog
{
public:
 CAboutDlg();

// Dialog Data
 //{ {AFX_DATA(CAboutDlg)
 enum { IDD = IDD_ABOUTBOX };
 //}}AFX_DATA

 // ClassWizard generated virtual function overrides
 //{ {AFX_VIRTUAL(CAboutDlg)
 protected:
 virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
 //}}AFX_VIRTUAL

// Implementation
protected:
 //{ {AFX_MSG(CAboutDlg)
 //}}AFX_MSG
 DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
 //{ {AFX_DATA_INIT(CAboutDlg)
 //}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
 CDialog::DoDataExchange(pDX);
 //{ {AFX_DATA_MAP(CAboutDlg)
 //}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
 //{ {AFX_MSG_MAP(CAboutDlg)
  // No message handlers
 //}}AFX_MSG_MAP
END_MESSAGE_MAP()

/
// CMthread1Dlg dialog

CMthread1Dlg::CMthread1Dlg(CWnd* pParent /*=NULL*/)
 : CDialog(CMthread1Dlg::IDD, pParent)
{
 //{ {AFX_DATA_INIT(CMthread1Dlg)
  // NOTE: the ClassWizard will add member initialization here
 //}}AFX_DATA_INIT
 // Note that LoadIcon does not require a subsequent DestroyIcon in Win32
 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CMthread1Dlg::DoDataExchange(CDataExchange* pDX)
{
 CDialog::DoDataExchange(pDX);
 //{ {AFX_DATA_MAP(CMthread1Dlg)
  // NOTE: the ClassWizard will add DDX and DDV calls here
 //}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CMthread1Dlg, CDialog)
 //{ {AFX_MSG_MAP(CMthread1Dlg)
 ON_WM_SYSCOMMAND()
 ON_WM_PAINT()
 ON_WM_QUERYDRAGICON()
 ON_BN_CLICKED(IDC_START, OnStart)
 ON_BN_CLICKED(IDC_STOP, OnStop)
 //}}AFX_MSG_MAP
END_MESSAGE_MAP()

/
// CMthread1Dlg message handlers

BOOL CMthread1Dlg::OnInitDialog()
{
 CDialog::OnInitDialog();

 // Add "About..." menu item to system menu.

 // IDM_ABOUTBOX must be in the system command ran

;